N-Queens LeetCode solution in C++

1
class Solution {
2
bool isSafe(vector<string> board, int row, int col, int n) {
3
int r = row;
4
int c = col;
5

6
// Checking for upper left diagonal
7
while (row >= 0 && col >= 0) {
8
if (board[row][col] == 'Q') return false;
9
row--;
10
col--;
11
}
12

13
row = r;
14
col = c;
15
// Checking for left
16
while (col >= 0) {
17
if (board[row][col] == 'Q') return false;
18
col--;
19
}
20

21
row = r;
22
col = c;
23
// Checking for lower left diagonal
24
while (row < n && col >= 0) {
25
if (board[row][col] == 'Q') return false;
26
row++;
27
col--;
28
}
29

30
return true;
31
}
32

33
void solve(vector<vector<string>> &ans, vector<string> &board, int n, int col) {
34
if (col == n) {
35
ans.push_back(board);
36
return;
37
}
38

39
for (int row = 0; row < n; row++) {
40
if (isSafe(board, row, col, n)) {
41
board[row][col] = 'Q';
42
solve(ans, board, n, col + 1);
43
board[row][col] = '.';
44
}
45
}
46
}
47

48
public:
49
vector<vector<string>> solveNQueens(int n) {
50
vector<vector<string>> ans;
51
vector<string> board;
52
string s(n, '.');
53
for (int i = 0; i < n; i++) board.push_back(s);
54

55
solve(ans, board, n, 0);
56

57
return ans;
58
}
59
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0