forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0051.cpp
More file actions
53 lines (39 loc) · 1.27 KB
/
Copy path0051.cpp
File metadata and controls
53 lines (39 loc) · 1.27 KB
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
class Solution {
vector<vector<string>> ans;
public:
bool isValid(vector<string>& board, int row, int col){
//column checking
for(int i = row; i >= 0; i--)
if(board[i][col] == 'Q')
return false;
//left diagonal
for(int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if(board[i][j] == 'Q')
return false;
//right diagonal
for(int i = row, j = col; i >= 0 && j < board.size(); i--, j++)
if(board[i][j] == 'Q')
return false;
return true;
}
void dfs(vector<string>& board, int row){
if(row == board.size()){
ans.push_back(board);
return;
}
for(int i = 0; i < board.size(); i++){
if(isValid(board, row, i)){
board[row][i] = 'Q';
dfs(board, row + 1);
board[row][i] = '.'; //bactracking
}
}
}
vector<vector<string>> solveNQueens(int n) {
if(n < 1)
return ans;
vector<string> board(n, string(n, '.'));
dfs(board, 0);
return ans;
}
};