LeetCode51. 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.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

回溯法

将一行string看做一个排列。初始都设为”.“。然后从col=0基于判断开始排列。判断函数是(1.col不重复。2.45°不重复。3.135°不重复。)满足这三个条件就设为”Q”。开始递归。递归的变量是row++。递归条件是row==n。结束递归之后。要回溯,保证前面的col的排列不变,都是”.”

细节

验证的时候,不用验证row上的Q只有一个。因为递归的参数是row+1。已经保证了。

N皇后:注意循环是指排列的col变动,从0开始;递归是指下一个string,row的变动。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> ret;
vector<string> myqueen(n,string(n,'.'));
Helper(ret,myqueen,n,0);
return ret;
}

void Helper(vector<vector<string>>&ret,vector<string> &myqueen,int n,int row){
if(row==n)
{
ret.push_back(myqueen);
return;
}
for(int col=0;col<n;col++)//排序的是col
{
if(!IsValid(myqueen,n,row,col))//基于条件对string进行排序。col是变量
continue;
myqueen[row][col]='Q';
Helper(ret,myqueen,n,row+1);//往myqueen的下一个string,所以是row+1
myqueen[row][col]='.';
}
}

bool IsValid(vector<string> myqueen,int n,int row,int col){
//row
// for(int c = col; c >=0; c--)
// {
// if(myqueen[row][c]=='Q')
// return false;
// }
//因为已经Helper(row+1),所以一行中只有一个Q是固定了的。


//col
for(int r=row;r>=0;r--)
{
if(myqueen[r][col]=='Q')
return false;
}

//45°
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
{
if(myqueen[i][j]=='Q')
return false;
}

//135°
for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++)
{
if(myqueen[i][j]=='Q')
return false;
}

return true;
}
};
Thanks for Support.