N-Queens

N-Queens

Description:

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:

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

[
    // Solution 1
    [“.Q..”,
    ”…Q”,
    ”Q…”,
    ”..Q.”
    ],
    // Solution 2
    [“..Q.”,
    ”Q…”,
    ”…Q”,
    ”.Q..”
    ]
]

分析:

Code:

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
class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<vector<string> > allSol;
vector<string> sol;
vector<int> col;

solveNQ(n, 0, col, sol, allSol);

return allSol;
}

void solveNQ(int rows, int currRow, vector<int> &col, vector<string> &sol, vector<vector<string> > &allSol) {
if (rows == currRow) {
allSol.push_back(sol);
return;
}

for (int i = 0; i < rows; i++) {
if (isValid(currRow, i, col)) {
string s(rows, '.');
s[i] = 'Q';

sol.push_back(s);
col.push_back(i);

solveNQ(rows, currRow + 1, col, sol, allSol);
sol.pop_back();
col.pop_back();
}
}
}

bool isValid(int currRow, int currCol, vector<int> &col) {
if (currRow < col.size()) return false;

for (int i = 0; i < col.size(); i++) {
if (currCol == col[i] || abs(currRow - i) == abs(currCol - col[i])) return false;
}

return true;
}
};