N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n 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 solve(vector<vector<string> >& result,
02            vector<string> cur, int n)
03 {
04     int m=cur.size();
05     if(m==n){
06         result.push_back(cur);
07         return;
08     }
09     bool table[n];
10     for(int i=0;i<n;i++){
11         table[i]=true;
12     }
13     for(int i=0;i<m;i++){
14         for(int j=0;j<n;j++){
15             if(cur[i][j]==‘Q’){
16                 table[j]=false;
17                 if(j(mi)>=0)
18                     table[j(mi)]=false;
19                 if(j+(mi)<n)
20                     table[j+(mi)]=false;
21             }
22         }
23     }
24     string tmp;
25     for(int i=0;i<n;i++)
26         tmp+=‘.’;
27     for(int i=0;i<n;i++){
28         if(table[i]==true){
29             tmp[i]=‘Q’;
30             cur.push_back(tmp);
31             solve(result,cur,n);
32             cur.pop_back();
33             tmp[i]=‘.’;
34         }
35     }
36 }
37 
38  vector<vector<string> > solveNQueens(int n)
39  {
40      vector<vector<string> > result;
41      if(n==0)
42          return result;
43      vector<string> cur;
44      solve(result,cur,n);
45      return result;
46  }
Advertisements
This entry was posted in Array and linked list, Backtrack. 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