-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0051.cpp
More file actions
executable file
·52 lines (45 loc) · 1.08 KB
/
LC0051.cpp
File metadata and controls
executable file
·52 lines (45 loc) · 1.08 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
/*
Problem Statement: https://leetcode.com/problems/n-queens/
Time: O(n!)
Space: O(n!)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> boards;
vector<string> board(n, string(n, '.'));
vector<int> row(n), col(n), dig(2 * n - 1), rdig(2 * n - 1);
// helper functions
auto valid = [&](int x, int y) {
return x >= 0 && x < n && y >= 0 && y < n;
};
auto taken = [&](int x, int y) {
return !valid(x, y) || row[x] || col[y] || dig[x - y + n - 1] || rdig[x + y];
};
auto mark = [&](int x, int y, bool val) {
if (!valid(x, y))
return;
row[x] = col[y] = dig[x - y + n - 1] = rdig[x + y] = val;
};
function<void(int)> dfs = [&](int i) {
// base case
if (i == n) {
boards.push_back(board);
return;
}
// backtracking
for (int j = 0; j < n; j++) {
if (taken(i, j))
continue;
mark(i, j, true);
board[i][j] = 'Q';
dfs(i + 1);
board[i][j] = '.';
mark(i, j, false);
}
};
dfs(0);
return boards;
}
};