码迷,mamicode.com
首页 > 其他好文 > 详细

52. N皇后 II

时间:2020-03-18 23:52:55      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:全局   pre   int   dfs   class   color   bool   als   思路   

思路跟51题一模一样

 1 class Solution 
 2 {
 3     vector<vector<string>> res;
 4     vector<string> temp;//临时路径
 5     vector<bool> col,m,s;//列,主对角线,副对角线
 6     int n;
 7 public:
 8     int totalNQueens(int N) 
 9     {
10         n = N;//将N设置成一个全局变量
11         temp = vector<string>(n,string(n,.));//n行,每一行有n个.
12         col = m = s = vector<bool>(2 * n,false);//标记数组大小设置稍大一点
13         dfs(0);
14         return res.size();
15     }
16 
17     void dfs(int x)//
18     {   // x == n 表示已经搜了n行
19         if(x == n)
20         {
21             res.push_back(temp);
22             return;
23         }
24         for(int y = 0;y < n;y ++)//对某一行的每一列进行搜索
25         {
26             if(!col[y] && !m[x + y] && !s[y - x + n])
27             {
28                 temp[x][y] = Q;
29                 col[y] = m[x + y] = s[y - x + n] = true;
30                 dfs(x + 1);
31                 
32                 // 恢复现场 这步很关键
33                 col[y] = m[x + y] = s[y - x + n] = false;
34                 temp[x][y] = .;
35             }
36         }
37     }
38 };

 

52. N皇后 II

标签:全局   pre   int   dfs   class   color   bool   als   思路   

原文地址:https://www.cnblogs.com/yuhong1103/p/12521042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!