-
Notifications
You must be signed in to change notification settings - Fork 66
/
Leetcode Solution
68 lines (61 loc) · 2.05 KB
/
Leetcode Solution
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
// LC :- 51 N-Queen Solution
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
// Creating the data structure
vector<vector<string>>answer;
vector<string>chessBoard(n);
string s(n, '.');
for(int i = 0; i < n; i++){
chessBoard[i] = s;
}
puzzle(0, chessBoard, answer, n);
return answer;
}
// Creating the recursive function
void puzzle(int currentCol, vector<string>&chessBoard, vector<vector<string>>&answer, int n){
// Base condition, when we traverse all the cell validity
if(currentCol == n){
answer.push_back(chessBoard);
return ;
}
for(int currentRow = 0; currentRow < n; currentRow++){
// Checking valid cell
if(isValid(currentRow, currentCol, chessBoard, n)){
chessBoard[currentRow][currentCol] = 'Q';
puzzle(currentCol + 1, chessBoard, answer, n);
chessBoard[currentRow][currentCol] = '.';
}
}
}
// Checking if given cell is valid
bool isValid(int row, int col, vector<string>&chessBoard, int n){
// Checking up-left diagonal
int currentRow = row;
int currentCol = col;
while(currentRow >= 0 && currentCol >= 0){
if(chessBoard[currentRow][currentCol] == 'Q')
return false;
currentRow--;
currentCol--;
}
// Checking whole left cell
currentRow = row;
currentCol = col;
while(currentCol >= 0){
if(chessBoard[currentRow][currentCol] == 'Q')
return false;
currentCol--;
}
// Checking down-left diagonal
currentRow = row;
currentCol = col;
while(currentRow < n && currentCol >= 0){
if(chessBoard[currentRow][currentCol] == 'Q')
return false;
currentRow++;
currentCol--;
}
return true;
}
};