Skip to content

Commit 69ec6e7

Browse files
authored
Create N-Queens
1 parent 975f033 commit 69ec6e7

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

精選高頻HARD題目/N-Queens

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
想法:利用 Recursive Backtracking 的技巧,嘗試每一行中的所有可能
2+
3+
Time Complexity : O(n^n) for n rows and each row has O(n) ways to put the queen
4+
Space Complexity : O(n^2) for the O(n^2) board
5+
6+
class Solution {
7+
public:
8+
vector<vector<string>> ans ;
9+
vector<string> board ;
10+
11+
bool valid(int row , int column , int n ) {
12+
// check column
13+
for(int i = 0 ; i < row ; i++) {
14+
if ( board[i][column] == 'Q' )
15+
return false ;
16+
}
17+
// check diagonal
18+
for(int r = 0 ; r < row ; r++) {
19+
int c1 = row + column - r ;
20+
int c2 = r - row + column ;
21+
if ( c1 < n && board[r][c1] == 'Q')
22+
return false ;
23+
if (c2 >= 0 && board[r][c2] == 'Q')
24+
return false ;
25+
}
26+
return true ;
27+
}
28+
29+
void findsolution( int n , int row) {
30+
if (row == n) {
31+
ans.push_back(board) ;
32+
return ;
33+
}
34+
35+
for(int i = 0 ; i < n ; i++) {
36+
if ( valid(row ,i , n) ) {
37+
board[row][i] = 'Q' ;
38+
findsolution(n , row + 1) ;
39+
board[row][i] = '.' ;
40+
}
41+
}
42+
return ;
43+
}
44+
45+
vector<vector<string>> solveNQueens(int n) {
46+
string s ;
47+
for(int i = 0 ; i < n ; i++)
48+
s += '.' ;
49+
for(int i = 0 ; i < n ; i++) {
50+
board.push_back(s) ;
51+
}
52+
53+
findsolution(n , 0) ;
54+
return ans ;
55+
}
56+
};

0 commit comments

Comments
 (0)