Skip to content

Commit a00d1bd

Browse files
committed
Create NQueens.cpp
Added Solution for the Problem NQueens.
1 parent d633401 commit a00d1bd

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

leetcode/NQueens.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// N Queens Problem - Leetcode
2+
// https://leetcode.com/problems/n-queens/
3+
class Solution
4+
{
5+
public:
6+
bool isSafe(int n, int row, int col, vector<string> board)
7+
{
8+
int dr = row;
9+
int dc = col;
10+
while (row >= 0 && col >= 0)
11+
{
12+
if (board[row][col] == 'Q')
13+
{
14+
return false;
15+
}
16+
row--;
17+
col--;
18+
}
19+
col = dc;
20+
row = dr;
21+
while (col >= 0)
22+
{
23+
if (board[row][col] == 'Q')
24+
{
25+
return false;
26+
}
27+
col--;
28+
}
29+
row = dr;
30+
col = dc;
31+
while (row < n && col >= 0)
32+
{
33+
if (board[row][col] == 'Q')
34+
{
35+
return false;
36+
}
37+
row++;
38+
col--;
39+
}
40+
41+
return true;
42+
}
43+
void solve(int n, int col, vector<string> &board, vector<vector<string>> &ans)
44+
{
45+
if (col == n)
46+
{
47+
ans.push_back(board);
48+
return;
49+
}
50+
51+
for (int row = 0; row < n; row++)
52+
{
53+
if (isSafe(n, row, col, board))
54+
{
55+
board[row][col] = 'Q';
56+
57+
solve(n, col + 1, board, ans);
58+
59+
board[row][col] = '.';
60+
}
61+
}
62+
}
63+
vector<vector<string>> solveNQueens(int n)
64+
{
65+
vector<vector<string>> ans;
66+
vector<string> board(n);
67+
string s(n, '.');
68+
for (int i = 0; i < n; i++)
69+
{
70+
board[i] = s;
71+
}
72+
solve(n, 0, board, ans);
73+
74+
return ans;
75+
}
76+
};

0 commit comments

Comments
 (0)