当前位置:   article > 正文

DFS——n皇后问题_n皇后问题dfs

n皇后问题dfs

n−皇后问题是指将 n 个皇后放在 n×n 的国际象棋棋盘上,使得皇后不能相互攻击到,即任意两个皇后都不能处于同一行、同一列或同一斜线上。

现在给定整数 n,请你输出所有的满足条件的棋子摆法。

输入格式

共一行,包含整数 n。

输出格式

每个解决方案占 n 行,每行输出一个长度为 n 的字符串,用来表示完整的棋盘状态。

其中 . 表示某一个位置的方格状态为空,Q 表示某一个位置的方格上摆着皇后。

每个方案输出完成后,输出一个空行。

注意:行末不能有多余空格。

输出方案的顺序任意,只要不重复且没有遗漏即可。

数据范围

1≤n≤9

输入样例:

4

输出样例:

  1. .Q..
  2. ...Q
  3. Q...
  4. ..Q.
  5. ..Q.
  6. Q...
  7. ...Q
  8. .Q..

第一种搜索方法:

Code:

  1. #include <iostream>
  2. #include <stdio.h>
  3. using namespace std;
  4. const int N = 23;
  5. int n;
  6. char g[N][N];
  7. bool col[N], dg[N], udg[N], row[N];
  8. void dfs(int x, int y, int s)
  9. {
  10. if(s > n) return ;
  11. if(y == n) y = 0, x ++;
  12. if (x == n)
  13. {
  14. if (s == n)
  15. {
  16. for (int i = 0; i < n; i ++ ) puts(g[i]);
  17. puts("");
  18. }
  19. return;
  20. }
  21. dfs(x, y + 1, s);//不放皇后, 向前走
  22. if(!col[y] && !row[x] && !dg[x + y] && !udg[x - y + n])
  23. {
  24. g[x][y] = 'Q';
  25. col[y] = row[x] = dg[x + y] = udg[x - y + n] = true;
  26. dfs(x, y + 1, s + 1);
  27. g[x][y] = '.';
  28. col[y] = row[x] = dg[x + y] = udg[x - y + n] = false;
  29. }
  30. }
  31. signed main()
  32. {
  33. scanf("%d", &n);
  34. for(int i = 0; i < n; i ++ )
  35. {
  36. for(int j = 0; j < n; j ++ ) g[i][j] = '.';
  37. }
  38. dfs(0, 0, 0);
  39. }

 第二种搜索方法:

Code:

  1. #include <iostream>
  2. #include <stdio.h>
  3. using namespace std;
  4. const int N = 23;
  5. int n;
  6. char g[N][N];
  7. bool col[N], dg[N], udg[N];
  8. void dfs(int x)
  9. {
  10. if(x == n)
  11. {
  12. for(int i = 0; i < n; i ++ ) puts(g[i]);
  13. puts("");
  14. }
  15. for(int i = 0; i < n; i ++ ) //从第0层开始搜
  16. {
  17. if(!col[i] && !dg[x + i] && !udg[x - i + n]) //剪枝
  18. {
  19. g[x][i] = 'Q';
  20. col[i] = dg[x + i] = udg[x - i + n] = true;
  21. dfs(x + 1);
  22. g[x][i] = '.';
  23. col[i] = dg[x + i] = udg[x - i + n] = false;
  24. }
  25. }
  26. }
  27. signed main()
  28. {
  29. scanf("%d", &n);
  30. for(int i = 0; i < n; i ++ )
  31. {
  32. for(int j = 0; j < n; j ++ ) g[i][j] = '.';
  33. }
  34. dfs(0);
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/825420
推荐阅读
相关标签
  

闽ICP备14008679号