标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2553
N皇后问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
-1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
-2 | -1 | 0 | 1 | 2 | 3 | 4 | 5 |
-3 | -2 | -1 | 0 | 1 | 2 | 3 | 4 |
-4 | -3 | -2 | -1 | 0 | 1 | 2 | 3 |
-5 | -4 | -3 | -2 | -1 | 0 | 1 | 2 |
-6 | -5 | -4 | -3 | -2 | -1 | 0 | 1 |
-7 | -6 | -5 | -4 | -3 | -2 | -1 | 0 |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int n, vis[11], cnt, ans[11]; 6 void Search(int cur){ 7 if (cur == n) cnt++; 8 else for (int i = 0; i < n; i++){ 9 int flag = 1; 10 vis[cur] = i; 11 for (int j = 0; j < cur; j++){ 12 if (vis[cur] == vis[j] || cur - vis[cur] == j - vis[j] || cur + vis[cur] == j + vis[j]){ 13 flag = 0; 14 break; 15 } 16 } 17 if (flag) Search(cur + 1); 18 } 19 } 20 int main(){ 21 memset(ans, -1, sizeof(ans)); 22 while (~scanf("%d", &n), n){ 23 //while (cin >> n, n){ 24 cnt = 0; 25 if (ans[n] != -1){ 26 printf("%d\n", ans[n]); 27 continue; 28 } 29 Search(0); 30 printf("%d\n", cnt); 31 ans[n] = cnt; 32 //cout << cnt << endl; 33 } 34 return 0; 35 }
如果要输出排列情况,代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int n, vis[11], cnt,T=1, ans[11]; 6 void Show(){ 7 for (int i = 0; i < n; i++){ 8 for (int j = 0; j < n; j++){ 9 if (j) cout << ‘ ‘; 10 if (j == vis[i]) cout << char(3); 11 else 12 cout << ‘.‘; 13 } 14 cout << endl; 15 } 16 } 17 void Search(int cur){ 18 if (cur == n){ 19 cout << "Case:" << T++ << endl; 20 Show(); 21 cnt++; 22 } 23 else for (int i = 0; i < n; i++){ 24 int flag = 1; 25 vis[cur] = i; 26 for (int j = 0; j < cur; j++){ 27 if (vis[cur] == vis[j] || cur - vis[cur] == j - vis[j] || cur + vis[cur] == j + vis[j]){ 28 flag = 0; 29 break; 30 } 31 } 32 if (flag) Search(cur + 1); 33 } 34 } 35 int main(){ 36 memset(ans, -1, sizeof(ans)); 37 while (cout<<"请输入皇后数:",cin >> n, n){ 38 T = 1; 39 cnt = 0; 40 Search(0); 41 cout << "总排列方式:"<<cnt << endl; 42 } 43 return 0; 44 }
[HDU 2553]--N皇后问题(回溯)/N皇后问题的分析
标签:
原文地址:http://www.cnblogs.com/zyxStar/p/4592219.html