1
1
class Solution {
2
2
public:
3
- vector<vector<string>> solveNQueens (int n) {
4
- // Start typing your C/C++ solution below
5
- // DO NOT write int main() function
6
-
7
- string row (n, ' .' );
8
- vector<string> queens (n, row);
9
-
10
- vector<bool > visited_col (n, false );
11
- vector<bool > visited_slope1 (2 *n-1 , false );
12
- vector<bool > visited_slope2 (2 *n-1 , false );
13
- vector<vector<bool >> visited;
14
- visited.push_back (visited_col);
15
- visited.push_back (visited_slope1);
16
- visited.push_back (visited_slope2);
17
-
3
+ vector<vector<string> > solveNQueens (int n) {
18
4
vector<vector<string>> result;
19
-
20
- generateNQueens (queens, visited, 0 , n, result);
5
+ if (n == 0 ) {
6
+ return result;
7
+ }
8
+ vector<string> sol (n, string (n, ' .' ));
9
+ vector<vector<bool >> visited (3 , vector<bool >(2 *n, false ));
10
+ dfs (result, sol, visited, 0 );
21
11
return result;
22
12
}
23
13
24
- void generateNQueens (vector<string>& queens, vector<vector<bool >>& visited,
25
- int row, int n, vector<vector<string>>& result) {
26
-
14
+ void dfs (vector<vector<string>>& result, vector<string>& sol, vector<vector<bool >>& visited, int row) {
15
+ int n = sol.size ();
27
16
if (row == n) {
28
- result.push_back (queens );
17
+ result.push_back (sol );
29
18
return ;
30
19
}
31
-
32
20
for (int col = 0 ; col < n; col++) {
33
- if (visited[0 ][col] == false &&
34
- visited[1 ][row+col] == false &&
35
- visited[2 ][n-1 -col+row] == false ) {
36
-
37
- queens[row][col] = ' Q' ;
38
- visited[0 ][col] = true ;
39
- visited[1 ][row+col] = true ;
40
- visited[2 ][n-1 -col+row] = true ;
41
-
42
- generateNQueens (queens, visited, row + 1 , n, result);
43
-
44
- queens[row][col] = ' .' ;
45
- visited[0 ][col] = false ;
46
- visited[1 ][row+col] = false ;
47
- visited[2 ][n-1 -col+row] = false ;
21
+ if (visited[0 ][col] || visited[1 ][row+col] || visited[2 ][n-1 -row+col]) {
22
+ continue ;
48
23
}
24
+ visited[0 ][col] = true ;
25
+ visited[1 ][row+col] = true ;
26
+ visited[2 ][n-1 -row+col] = true ;
27
+ sol[row][col] = ' Q' ;
28
+ dfs (result, sol, visited, row + 1 );
29
+ sol[row][col] = ' .' ;
30
+ visited[0 ][col] = false ;
31
+ visited[1 ][row+col] = false ;
32
+ visited[2 ][n-1 -row+col] = false ;
49
33
}
50
34
}
51
- };
35
+ };
0 commit comments