Cover image for Interview Classic 150 Questions P52 N-Queens II

Interview Classic 150 Questions P52 N-Queens II


Timeline

Timeline

2025-11-30

init


Problem:

Classic backtracking problem, consider that each row can only and must place one queen, then each backtrack considers where to place the next row.
Note that when marking areas that can be attacked, use -1 instead of assigning -1. This is to avoid two queens being able to attack the same area simultaneously.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <vector>
using std::vector;

class Solution {
private:
int cnt;
void backtrace(vector<vector<int> > &board, int row, int n)
{
if (row == n) {
this->cnt++;
return;
}
int i, j, k;
for (j = 0; j < n; j++) { // column
if (board[row][j] == 0) {
for (i = row + 1; i < n; i++) { //set column of other row
board[i][j] -= 1;
}
i = row + 1;
k = j + 1;
while (i < n && k < n) {
board[i][k] -= 1;
i++;
k++;
}
i = row + 1;
k = j - 1;
while (i < n && k >= 0) {
board[i][k] -= 1;
i++;
k--;
}

board[row][j] = 1;

backtrace(board, row + 1, n);

i = row + 1;
k = j + 1;
while (i < n && k < n) {
board[i][k] += 1;
i++;
k++;
}
i = row + 1;
k = j - 1;
while (i < n && k >= 0) {
board[i][k] += 1;
i++;
k--;
}
for (i = row + 1; i < n; i++) { //set column of other row
board[i][j] += 1;
}
board[row][j] = 0;
}
}
}

public:
int totalNQueens(int n)
{
this->cnt = 0;

vector<vector<int> > board = vector(n, vector<int>(n, 0));
backtrace(board, 0, n);
return cnt;
}
};

int main()
{
Solution S;
S.totalNQueens(4);
}