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

51. N皇后

时间:2019-09-26 10:08:46      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:oid   back   backtrack   col   public   for   backtrac   att   span   

待完善

 1 class Solution {
 2 public:
 3     
 4 int* queens;
 5 int* rows;
 6 int* dales;
 7 int* hills;
 8 int m = 0;
 9 vector<vector<string>> res;
10 bool attcked(int row,int col)
11 {
12     int res = rows[col] + dales[row+col] + hills[row-col+m];
13     if (res)
14         return true;
15     else
16         return false;
17 }
18 void put(int row,int col)
19 {
20     queens[row] = col;
21     rows[col] = 1;
22     dales[row + col] = 1;
23     hills[row - col + m] = 1;
24 }
25 void remove(int row, int col)
26 {
27     queens[row] = 0;
28     rows[col] = 0;
29     dales[row + col] = 0;
30     hills[row - col + m] = 0;
31 }
32 void getsolution(int row,int col)
33 {
34     vector<string> tempres;
35     for (int i = 0; i < m; i++)
36     {
37         int index = queens[i];
38         string temp;
39         for (int j = 0; j < index; j++)
40         {
41             temp.append(".");
42         }
43         temp.append("Q");
44         for (int j = 0; j < m - index - 1; j++)
45             temp.append(".");
46         tempres.push_back(temp);
47     }
48     res.push_back(tempres);
49 }
50 void backtrack(int row)
51 {
52     for(int col=0;col<m;col++)
53     {
54         if (attcked(row, col) == false)
55         {
56             put(row, col);
57             if (row + 1 == m)
58                 getsolution(row,col);
59             else
60                 backtrack(row + 1);
61             remove(row, col);
62         }
63     }
64 }
65     vector<vector<string>> solveNQueens(int n) {
66             m = n;
67     queens=new int[n];
68     rows = new int[n];
69     for (int i = 0; i < n; i++)
70     {
71         queens[i] = 0;
72         rows[i] = 0;
73     }
74     dales=new int[2*n];
75     hills=new int[2*n];
76     for (int i = 0; i < 2*n; i++)
77     {
78         dales[i] = 0;
79         hills[i] = 0;
80     }
81     backtrack(0);
82     return res;
83     }
84 };

 

51. N皇后

标签:oid   back   backtrack   col   public   for   backtrac   att   span   

原文地址:https://www.cnblogs.com/zouma/p/11588714.html

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