forked from shrutiv1000/Algorithms_misc_codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode - n queens.cpp
62 lines (47 loc) · 1.14 KB
/
leetcode - n queens.cpp
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
// leetcode - n queens
// https://leetcode.com/problems/n-queens/
vector<vector<string>> ans;
bool inBoard(int x, int y, int n) {
return (x >= 0 and x < n and y >= 0 and y < n);
}
bool isSafe(vector<string> board, int n, int x, int y) {
for (int i = 0 ; i < n ; i++)
if (board[i][y] == 'Q' or board[x][i] == 'Q')
return false;
for (int i = -n ; i < n ; i++)
if (inBoard(x + i, y + i, n) and board[x + i][y + i] == 'Q')
return false;
for (int i = -n ; i < n ; i++)
if (inBoard(x - i, y + i, n) and board[x - i][y + i] == 'Q')
return false;
return true;
}
void solve(vector<string> board, int n, int queens, int row)
{
if (queens == 0) {
ans.push_back(board);
return;
}
for (int i = 0 ; i < n ; i++) {
int x = row;
int y = i;
if (inBoard(x, y, n) and isSafe(board, n, x , y)) {
board[x][y] = 'Q';
solve(board, n, queens - 1, row + 1);
board[x][y] = '.';
}
}
}
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
ans.clear();
int queens = n;
string temp;
for (int i = 0 ; i < n; i++)
temp += '.';
vector<string> board(n, temp);
solve(board, n, queens, 0);
return ans;
}
};