-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51. N-Queens ( Leetcode )
72 lines (60 loc) · 1.64 KB
/
51. N-Queens ( Leetcode )
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
69
70
71
72
class Solution {
public:
bool isSafe(int size, int row, int col, vector<string> testBoard)
{
int tempCol = col;
int tempRow = row;
while(row >= 0 && col >= 0)
{
if(testBoard[row][col] == 'Q') return false;
row--;
col--;
}
col = tempCol;
row = tempRow;
while( col >= 0)
{
if(testBoard[row][col] == 'Q') return false;
col--;
}
col = tempCol;
row = tempRow;
while(row < size && col >= 0)
{
if(testBoard[row][col] == 'Q') return false;
row++;
col--;
}
return true;
}
void helper(vector<vector<string>> &chessBoard, vector<string> &testBoard, int col, int size)
{
if(col == size)
{
chessBoard.push_back(testBoard);
return;
}
// doing simple backtracking
for(int i = 0; i < size; i++)
{
if(isSafe(size, i, col, testBoard))
{
testBoard[i][col] = 'Q';
helper(chessBoard, testBoard, col+1, size);
testBoard[i][col] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>> chessBoard;
// doing this to make the board according to the
// given questions requirment
vector<string> testBoard(n);
string s(n, '.');
for(int i = 0; i < n; i++) testBoard[i] = s;
int col = 0;
helper(chessBoard, testBoard, col, n);
return chessBoard;
}
};