## 这是一道简单的深度优先搜索问题##
附上题目链接:https://vjudge.net/problem/UVA-639
这道题跟八皇后问题类似,思路大致为:把棋盘的每一格视作一个状态,符合要求就摆放,不符合就进入下一状态,到达最后一格就开始回溯,直至走完每一个状态,由于是每一次都走到最后一格,符合深度优先搜索的思路。
附上AC代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 using namespace std; 7 int vis[4][4];//保存状态,1为放置,0为不放 8 char bor[4][4];//保存棋盘状态 9 int n, maxn; 10 11 /*判断该格是否能放置車*/ 12 bool judge(int x, int y){ 13 int flag = 1; 14 if (bor[x][y] == 'X') return false; 15 for (int i = x+1; i < n; i++){ 16 if (bor[i][y] == 'X') break; 17 if (vis[i][y] == 1) flag = 0; 18 } 19 for (int i = x-1; i >= 0; i--){ 20 if (bor[i][y] == 'X') break; 21 if (vis[i][y] == 1) flag = 0; 22 } 23 for (int i = y+1; i < n; i++){ 24 if (bor[x][i] == 'X') break; 25 if (vis[x][i] == 1) flag = 0; 26 } 27 for (int i = y-1; i >= 0; i--){ 28 if (bor[x][i] == 'X') break; 29 if (vis[x][i] == 1) flag = 0; 30 } 31 return flag; 32 } 33 34 void dfs(int cur, int cnt){ 35 if (cur == n*n){ 36 maxn = maxn>cnt?maxn:cnt; 37 return; 38 } 39 if (judge(cur/n, cur%n)){ 40 vis[cur/n][cur%n] = 1; 41 dfs(cur+1, cnt+1); 42 vis[cur/n][cur%n] = 0; 43 dfs(cur+1, cnt); 44 } 45 else dfs(cur+1, cnt); 46 } 47 48 int main() 49 { 50 while(cin>>n&&n){ 51 for (int i = 0; i < n; i++) 52 for (int j = 0; j < n; j++) 53 cin>>bor[i][j]; 54 for (int i = 0; i < n*n; i++){ 55 dfs(i, 0); 56 memset(vis, 0, sizeof(vis)); 57 } 58 cout<<maxn<<endl; 59 maxn = 0; 60 memset(bor, 0, sizeof(bor)); 61 } 62 63 return 0; 64 }