鱼C论坛

 找回密码
 立即注册
查看: 1689|回复: 0

[技术交流] C++刷leetcode(面试题 08.12. 八皇后)【深度优先搜索】

[复制链接]
发表于 2020-4-14 15:39:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 17:33 编辑

题目描述:
  1. 设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。

  2. 注意:本题相对原题做了扩展

  3. 示例:

  4. 输入:4
  5. 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
  6. 解释: 4 皇后问题存在如下两个不同的解法。
  7. [
  8.  [".Q..",  // 解法 1
  9.   "...Q",
  10.   "Q...",
  11.   "..Q."],

  12.  ["..Q.",  // 解法 2
  13.   "Q...",
  14.   "...Q",
  15.   ".Q.."]
  16. ]

  17. 来源:力扣(LeetCode)
  18. 链接:https://leetcode-cn.com/problems/eight-queens-lcci
  19. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码




  1. #include<string>
  2. #include<vector>
  3. #include<iostream>

  4. using namespace std;

  5. bool valid(vector<int>& pos, int x, int y){
  6.         for(int i = 0; i < pos.size(); i++){
  7.                 if(i == x || y == pos[i] || x + y == i + pos[i] || x + pos[i] == y + i)return false;
  8.                
  9.         }
  10.         return true;
  11. }



  12. void dfs(int n, int x, vector<int>& pos, vector<string>& temp, vector<vector<string> >& res){
  13.         if(x == n) res.push_back(temp);
  14.         for(int y= 0 ; y < n; y ++){
  15.                 if(valid(pos, x, y)){
  16.                         temp[x][y] = 'Q';
  17.                         pos.push_back(y);
  18.                         dfs(n, x+1, pos, temp, res);
  19.                         pos.pop_back();
  20.                         temp[x][y] = '.';
  21.                 }       
  22.         }
  23. }



  24. vector<vector<string> > solution(int n){
  25.         vector<vector<string> > res;
  26.         vector<string>temp (n, string(n, '.'));
  27.         vector<int> pos;
  28.         dfs(n, 0, pos, temp, res);
  29.         return res;
  30. }




  31. int main(void){
  32.         int n;
  33.         cin >> n;
  34.         vector<vector<string> > res = solution(n);
  35.         for(int i = 0; i < res.size(); i++){
  36.                 for(int j = 0; j < res[i].size(); j++){
  37.                         cout << res[i][j] <<  endl;
  38.                 }
  39.                 cout << endl;
  40.                 cout << "------------------" << endl;
  41.         }
  42.         return 0;
  43. }
复制代码


参考链接:
1.x + y == i + pos[i] || x + pos[i] == y + i  可参见链接:https://leetcode-cn.com/problems ... u-zu-ji-lu-dui-jia/

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-29 19:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表