-
Notifications
You must be signed in to change notification settings - Fork 1
/
056_N Queens.cpp
140 lines (105 loc) · 2.67 KB
/
056_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Time Complexity -> O(N!)
// Space Complexity -> O(N^2)
bool isSafe(int row, int col, int n, vector<vector<int>>& board)
{
int dupRow = row;
int dupCol = col;
while(dupRow >= 0 and dupCol >= 0)
{
if(board[dupRow][dupCol] == 1)
return false;
--dupRow;
--dupCol;
}
dupRow = row;
dupCol = col;
while(dupCol >= 0)
{
if(board[dupRow][dupCol] == 1)
return false;
--dupCol;
}
dupCol = col;
dupRow = row;
while(dupRow < n and dupCol >= 0)
{
if(board[dupRow][dupCol] == 1)
return false;
--dupCol;
++dupRow;
}
return true;
}
void helper(int col, int n, vector<vector<int>>&board, vector<vector<int>>& ans)
{
if(col == n)
{
vector<int> curr;
for(auto itr : board)
{
for(auto x : itr)
{
curr.push_back(x);
}
}
ans.push_back(curr);
return;
}
for(int row = 0; row < n; ++row)
{
if(isSafe(row, col, n, board))
{
board[row][col] = 1;
helper(col+1, n, board, ans);
board[row][col] = 0;
}
}
}
vector<vector<int>> solveNQueens(int n) {
// Write your code here.
vector<vector<int>> ans;
vector<vector<int>> board(n, vector<int>(n,0));
helper(0, n, board, ans);
return ans;
}
// Time Complexity -> O(N!)
// Space Complexity -> O(N^2)
void helper(int col, int n, vector<vector<int>>&board, vector<int>&leftRow, vector<int>& upperDiag, vector<int>& lowerDiag, vector<vector<int>>& ans)
{
if(col == n)
{
vector<int> curr;
for(auto itr : board)
{
for(auto x : itr)
{
curr.push_back(x);
}
}
ans.push_back(curr);
return;
}
for(int row = 0; row < n; ++row)
{
if(!leftRow[row] and !lowerDiag[row + col] and !upperDiag[n-1 + (col-row)])
{
board[row][col] = 1;
leftRow[row] = 1;
lowerDiag[row + col] = 1;
upperDiag[n-1 + (col - row)] = 1;
helper(col+1, n, board, leftRow, upperDiag, lowerDiag, ans);
board[row][col] = 0;
leftRow[row] = 0;
lowerDiag[row + col] = 0;
upperDiag[n-1 + (col - row)] = 0;
}
}
}
vector<vector<int>> solveNQueens(int n) {
// Write your code here.
vector<vector<int>> ans;
vector<vector<int>> board(n, vector<int>(n,0));
vector<int> leftRow(n,0), lowerDiag(2*n-1,0), upperDiag(2*n-1, 0);
helper(0, n, board, leftRow, lowerDiag, upperDiag, ans);
return ans;
}