N-Queens

The n-queens puzzle is the problem of placing n queens on an nn chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
C++:
01 void solveNQueensHelper(int n, int row,
02                         vector<vector<string>>& result, vector<string>& cur)
03 {
04     if(row==n)
05     {
06         result.push_back(cur);
07         return;
08     }
09     for(int i=0;i<n;i++)
10     {
11         bool flag=true;
12         for(int j=row1;j>=0;j)
13         {
14             if(cur[j][i]=='Q')
15             {
16                 flag=false;
17                 break;
18             }
19             if((i+rowj<n)&&(cur[j][i+rowj]=='Q'))
20             {
21                 flag=false;
22                 break;
23             }
24             if((irow+j>=0)&&(cur[j][irow+j]=='Q'))
25             {
26                 flag=false;
27                 break;
28             }
29         }
30         if(flag==false)
31             continue;
32         string s(n,'.');
33         s[i]='Q';
34         cur.push_back(s);
35         solveNQueensHelper(n,row+1,result,cur);
36         cur.pop_back();
37     }
38 }
39 class Solution {
40 public:
41     vector<vector<string> > solveNQueens(int n) {
42         // Start typing your C/C++ solution below
43         // DO NOT write int main() function
44         vector<vector<string>> result;
45         vector<string> S;
46         solveNQueensHelper(n,0,result,S);
47         return result;
48     }
49 };
Advertisements
This entry was posted in Backtrack, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s