连接是:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=580
AC了。依旧是回溯法。跟生成binary的array的所有情况是差不多的implementation。


1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 const int MAXGRID = 4; 6 char grid[MAXGRID][MAXGRID]; 7 int vis[MAXGRID][MAXGRID]; 8 int lines; 9 10 bool isRowValid(int row, int col){ 11 if (grid[row][col] == 'X') 12 return false; 13 for (int j = col-1; j >= 0; j--){ 14 if (vis[row][j]) 15 return false; 16 else if (grid[row][j] == 'X') 17 return true; 18 } 19 return true; 20 } 21 22 bool isColValid(int row, int col){ 23 if (grid[row][col] == 'X') 24 return false; 25 for (int i = row-1; i >= 0; i--){ 26 if (vis[i][col]) 27 return false; 28 else if (grid[i][col] == 'X') 29 return true; 30 } 31 return true; 32 } 33 34 void search(int& max, int temp_max, int row, int col){ 35 if (lines == col){ 36 if (max < temp_max) 37 max = temp_max; 38 // cout << endl; 39 } 40 else{ 41 // cout << "(" << row << "," << col << ")" << " "; 42 int new_row = row+1, new_col = col; 43 if (new_row == lines){ 44 new_row = 0; 45 new_col++; 46 } 47 if (isRowValid(row,col) && isColValid(row,col)){ 48 vis[row][col] = 1; 49 search(max, temp_max+1, new_row, new_col); 50 } 51 vis[row][col] = 0; 52 search(max, temp_max, new_row, new_col); 53 } 54 } 55 56 int main(int argc, char *argv[]){ 57 while (cin >> lines && lines){ 58 for (int row = 0; row < lines; row++){ 59 cin >> grid[row]; 60 } 61 // memset(vis, 0, sizeof(vis)); 62 for (int i = 0; i < lines; i++){ 63 for (int j = 0; j < lines; j++){ 64 vis[i][j] = 0; 65 } 66 } 67 68 int max = 0; 69 70 search(max, 0, 0, 0); 71 cout << max << endl; 72 } 73 return 0; 74 }