二维数组上的回溯 #include <iostream> #include <cstring> #include <cstdio> #include <cmath> #define m map using namespace std ; const int maxn = 5 ; int n , ans , vis[maxn][maxn] ; char map[maxn][maxn] ; void init() { ans = 0 ; memset( vis , 0 , sizeof( vis ) ) ; memset( map , 0 , sizeof( map ) ) ; return ; } void input() { for( int i = 0 ; i < n ; ++i ) cin >> map[i] ; return ; } bool is_ok( int x , int y ) { // if( !( map[x][y] ^ 'X' ) ) // return false ; if( map[x][y] == 'X' ) return false ; if( !( vis[x][y] ^ 1 ) ) return false ; for( int i = x-1 ; i>= 0 && map[i][y] != 'X' ; --i ) { if( !( vis[i][y] ^ 1 ) ) return false ; } for( int i = y - 1 ; i >= 0 && map[x][i] != 'X' ; --i ) { if( !( vis[x][i] ^ 1 ) ) return false ; } return true ; } void dfs( int x , int y , int tans ) { // cout << x << " " << y << endl ; if( x > n-1 ) { // cout << tans << endl ; if( tans > ans ) ans = tans ; return ; } if( is_ok( x , y ) ) { vis[x][y] = 1 ; if( y >= n-1 ) { dfs( x+1 , 0 , tans+1 ) ; } else { dfs( x , y+1 , tans+1 ) ; } vis[x][y] = 0 ; } if( y >= n-1 ) dfs( x+1 , 0 , tans ) ; else dfs( x , y+1 , tans ) ; return ; } void output() { cout << ans << endl ; return ; } int main() { while( cin >> n && n ) { init() ; input() ; dfs( 0 , 0 , 0 ) ; output() ; } return 0 ; }