Guarding the Chessboard UVA
来源:互联网 发布:千驮谷日本语学校 知乎 编辑:程序博客网 时间:2024/05/07 07:34
经典的八皇后问题,一个皇后放置在棋盘上,可以攻击对应的行、对应的列、右上的对角线以及右下的对角线,那么我们就用一个二维数组visit[4][35],对于每一个方格,假设这个方格的坐标是i和j,那么用i来标志对应的行,用j来标志对应的列,用i+j来标志对应的右上的对角线,利用i-j+11来标志对应的右下的对角线(因为i与j最大的差值为9),那么现在就可以利用dfs来进行递归求解了,每次将能够使用的皇后的个数增加,在对应的个数下,判断是否有解,如果有解,那么输出最终的皇后的个数就可以了,如果没有解,就将个数增加1,递归地进行查找与判断就行了,具体实现见如下代码:
#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>#include<functional>using namespace std;int n, m;char area[15][15];int people;bool visit[4][35];//0 行 1 列 2 右上对角线 3 左下对角线bool dfs(int x,int y,int amount){if (amount == people){for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (area[i][j] == 'X'&&!visit[0][i] &&!visit[1][j] && !visit[2][i + j] && !visit[3][i - j + 11]){return false;}}}return true;}while(x< n){while(y< m){bool temp1 = visit[0][x], temp2 = visit[1][y], temp3 = visit[2][x + y],temp4 = visit[3][x - y + 11];visit[0][x] = visit[1][y] = visit[2][x + y] = visit[3][x - y + 11] = true;if (dfs(x+1,0,amount + 1)) return true;visit[0][x] = temp1, visit[1][y] = temp2, visit[2][x + y] = temp3,visit[3][x - y + 11] = temp4;y++;}y = 0;x++;}return false;}int main(){int Case = 0;while (cin >> n){if (n == 0) break;Case++;cin >> m;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++)cin >> area[i][j];}for (people = 0; people < 5; people++){memset(visit,0,sizeof(visit));if (dfs(0,0,0)) break;}cout <<"Case "<<Case<<": "<<people << endl;}}
阅读全文
0 0
- Guarding the Chessboard UVA
- Guarding the Chessboard UVA
- Guarding the Chessboard UVA
- UVa 11214 Guarding the Chessboard
- UVa 11214 - Guarding the Chessboard
- UVA 11214 Guarding the Chessboard
- UVa 11214 - Guarding the Chessboard
- UVa 11214:Guarding the Chessboard(DFS)
- UVA 11214(p217)----Guarding the Chessboard
- UVA 11214 Guarding the Chessboard(回溯)
- UVa11214 - Guarding the Chessboard
- 11214 - Guarding the Chessboard
- UVa #11214 Guarding the Chessboard (习题7-10)
- UVa 11214 - Guarding the Chessboard(迭代加深搜索)
- 习题7-10 UVA 11214 Guarding the Chessboard (迭代加深搜索)
- 11214 - Guarding the Chessboard(暴力搜索)
- Uva11214 Guarding the Chessboard【dfs回溯】【习题7-10】
- Guarding the Farm
- 探探左滑右滑简单实现
- 安卓RSA加密解密
- FCC ID认证简介
- 文件的搜索---find
- 解决RecycleView嵌套RecycleView滑动冲突问题
- Guarding the Chessboard UVA
- PCA原理
- CS Academy cube coloring(Burnside lemma)
- 05.开源项目--git文件重命名
- 数据库锁机制 很详细的教程,易懂
- Atitit r2017 r3 doc list on home ntpc.docx
- 移动端扫一扫车牌,识别出结果
- Cognos配置ODBC数据源
- 判断集合是否为空