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

[LeetCode] N-Queens

时间:2015-07-01 22:08:25      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

The idea is to use backtracking. In fact, the code below uses DFS, which involves backtracking in a recursive manner.

The idea is also very simple. Starting from the first row, try each column. If it does not induce any attack, move on to the next row based on the configurations of the previous rows. Otherwise, backtrack to the current row and try another selection of the column position. Once we reach the last row, add the current setting to a vector<vector<string> >.

The code below is referenced to this link, which records the positions of the queens using a nice 1d array like a[row] = col to indicate there is a queen at (row, col).

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<vector<string>> solveNQueens(int n) {
 4         vector<vector<string> > queens;
 5         vector<int> colPos(n, 0);
 6         solve(colPos, n, 0, queens);
 7         return queens;
 8     }
 9 private:
10     bool noAttack(vector<int>& colPos, int row, int col) {
11         for (int r = row - 1, ld = col - 1, rd = col + 1; r >= 0; r--, ld--, rd++)
12             if (colPos[r] == col || colPos[r] == ld || colPos[r] == rd)
13                 return false;
14         return true;
15     }
16     vector<string> queenStr(vector<int>& colPos) {
17         int n = colPos.size();
18         vector<string> queen(n, string(n, .));
19         for (int i = 0; i < n; i++)
20             queen[i][colPos[i]] = Q;
21         return queen;
22     }
23     void solve(vector<int>& colPos, int n, int row, vector<vector<string> >& queens) {
24         if (row == n) {
25             queens.push_back(queenStr(colPos));
26             return;
27         }
28         for (int col = 0; col < n; col++) {
29             colPos[row] = col;
30             if (noAttack(colPos, row, col))
31                 solve(colPos, n, row + 1, queens);
32         }
33     }
34 };

 

[LeetCode] N-Queens

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4614567.html

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