-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnQueens.cpp
More file actions
97 lines (83 loc) · 1.73 KB
/
nQueens.cpp
File metadata and controls
97 lines (83 loc) · 1.73 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
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isSafe(vector<string> &board, int row, int col, int n)
{
// horizontally
for (int j = 0; j < n; j++)
{
if (board[row][j] == 'Q')
{
return false;
}
}
// vertically
for (int i = 0; i < n; i++)
{
if (board[i][col] == 'Q')
{
return false;
}
}
// left diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j] == 'Q')
{
return false;
}
}
// right diagonal
for (int i = row, j = col; i >= 0 && j < n; i--, j++)
{
if (board[i][j] == 'Q')
{
return false;
}
}
return true;
}
void nQueens(vector<string> &board, int row, int n, vector<vector<string>> &ans)
{
if (row == n)
{
ans.push_back({board});
return;
}
for (int j = 0; j < n; j++)
{
if (isSafe(board, row, j, n))
{
board[row][j] = 'Q';
nQueens(board, row + 1, n, ans);
board[row][j] = '.'; // backtracking
}
}
}
vector<vector<string>> solveNQueens(int n)
{
vector<string> board(n, string(n, '.'));
vector<vector<string>> ans;
nQueens(board, 0, n, ans);
return ans;
}
void printBoard(const vector<string> &board)
{
for (const string &row : board)
{
cout << row << endl;
}
cout << endl;
}
int main()
{
int n = 4;
vector<vector<string>> solutions = solveNQueens(n);
cout << "Total solutions for n = " << n << ": " << solutions.size() << endl;
for (const auto &solution : solutions)
{
printBoard(solution);
}
return 0;
}