赞
踩
n−皇后问题是指将 n 个皇后放在 n×n 的国际象棋棋盘上,使得皇后不能相互攻击到,即任意两个皇后都不能处于同一行、同一列或同一斜线上。
现在给定整数 n,请你输出所有的满足条件的棋子摆法。
输入格式
共一行,包含整数 n。
输出格式
每个解决方案占 n 行,每行输出一个长度为 n 的字符串,用来表示完整的棋盘状态。
其中 .
表示某一个位置的方格状态为空,Q
表示某一个位置的方格上摆着皇后。
每个方案输出完成后,输出一个空行。
注意:行末不能有多余空格。
输出方案的顺序任意,只要不重复且没有遗漏即可。
数据范围
1≤n≤9
输入样例:
4
输出样例:
- .Q..
- ...Q
- Q...
- ..Q.
-
- ..Q.
- Q...
- ...Q
- .Q..
第一种搜索方法:
Code:
- #include <iostream>
- #include <stdio.h>
-
- using namespace std;
-
- const int N = 23;
-
- int n;
- char g[N][N];
- bool col[N], dg[N], udg[N], row[N];
-
- void dfs(int x, int y, int s)
- {
- if(s > n) return ;
- if(y == n) y = 0, x ++;
- if (x == n)
- {
- if (s == n)
- {
- for (int i = 0; i < n; i ++ ) puts(g[i]);
- puts("");
- }
- return;
- }
- dfs(x, y + 1, s);//不放皇后, 向前走
-
- if(!col[y] && !row[x] && !dg[x + y] && !udg[x - y + n])
- {
- g[x][y] = 'Q';
- col[y] = row[x] = dg[x + y] = udg[x - y + n] = true;
- dfs(x, y + 1, s + 1);
- g[x][y] = '.';
- col[y] = row[x] = dg[x + y] = udg[x - y + n] = false;
- }
- }
-
- signed main()
- {
- scanf("%d", &n);
- for(int i = 0; i < n; i ++ )
- {
- for(int j = 0; j < n; j ++ ) g[i][j] = '.';
- }
- dfs(0, 0, 0);
- }
第二种搜索方法:
Code:
- #include <iostream>
- #include <stdio.h>
-
- using namespace std;
-
- const int N = 23;
-
- int n;
- char g[N][N];
- bool col[N], dg[N], udg[N];
-
- void dfs(int x)
- {
- if(x == n)
- {
- for(int i = 0; i < n; i ++ ) puts(g[i]);
- puts("");
- }
-
- for(int i = 0; i < n; i ++ ) //从第0层开始搜
- {
- if(!col[i] && !dg[x + i] && !udg[x - i + n]) //剪枝
- {
- g[x][i] = 'Q';
- col[i] = dg[x + i] = udg[x - i + n] = true;
- dfs(x + 1);
- g[x][i] = '.';
- col[i] = dg[x + i] = udg[x - i + n] = false;
- }
- }
- }
-
- signed main()
- {
- scanf("%d", &n);
- for(int i = 0; i < n; i ++ )
- {
- for(int j = 0; j < n; j ++ ) g[i][j] = '.';
- }
- dfs(0);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。