Skip to content

Commit 6b46d76

Browse files
committed
n queens using recursion
1 parent 1af903a commit 6b46d76

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

Recursion/nQueens.cpp

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <string>
4+
using namespace std;
5+
6+
bool isSafe(vector<string> &board, int row, int col, int n)
7+
{
8+
// horizontally
9+
for (int j = 0; j < n; j++)
10+
{
11+
if (board[row][j] == 'Q')
12+
{
13+
return false;
14+
}
15+
}
16+
17+
// vertically
18+
for (int i = 0; i < n; i++)
19+
{
20+
if (board[i][col] == 'Q')
21+
{
22+
return false;
23+
}
24+
}
25+
26+
// left diagonal
27+
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
28+
{
29+
if (board[i][j] == 'Q')
30+
{
31+
return false;
32+
}
33+
}
34+
35+
// right diagonal
36+
for (int i = row, j = col; i >= 0 && j < n; i--, j++)
37+
{
38+
if (board[i][j] == 'Q')
39+
{
40+
return false;
41+
}
42+
}
43+
44+
return true;
45+
}
46+
47+
void nQueens(vector<string> &board, int row, int n, vector<vector<string>> &ans)
48+
{
49+
if (row == n)
50+
{
51+
ans.push_back({board});
52+
return;
53+
}
54+
55+
for (int j = 0; j < n; j++)
56+
{
57+
if (isSafe(board, row, j, n))
58+
{
59+
board[row][j] = 'Q';
60+
nQueens(board, row + 1, n, ans);
61+
board[row][j] = '.'; // backtracking
62+
}
63+
}
64+
}
65+
66+
vector<vector<string>> solveNQueens(int n)
67+
{
68+
vector<string> board(n, string(n, '.'));
69+
vector<vector<string>> ans;
70+
71+
nQueens(board, 0, n, ans);
72+
return ans;
73+
}
74+
75+
void printBoard(const vector<string> &board)
76+
{
77+
for (const string &row : board)
78+
{
79+
cout << row << endl;
80+
}
81+
cout << endl;
82+
}
83+
84+
int main()
85+
{
86+
int n = 4;
87+
vector<vector<string>> solutions = solveNQueens(n);
88+
89+
cout << "Total solutions for n = " << n << ": " << solutions.size() << endl;
90+
91+
for (const auto &solution : solutions)
92+
{
93+
printBoard(solution);
94+
}
95+
96+
return 0;
97+
}

Recursion/nQueens.exe

109 KB
Binary file not shown.

0 commit comments

Comments
 (0)