-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueenSimpleSol.cpp
More file actions
52 lines (46 loc) · 882 Bytes
/
NQueenSimpleSol.cpp
File metadata and controls
52 lines (46 loc) · 882 Bytes
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
#include <iostream>
using namespace std;
const int size=10;
int board[size];
// check if row, col is a valid position to place the queen
bool okayPosition(int row, int col) {
for (int i = 0; i < row; i++)
{
int other_row_pos = board[i];
if (other_row_pos == col ||
other_row_pos == col - (row - i) ||
other_row_pos == col + (row - i))
return false;
}
return true;
}
bool solveNQueens(int row) {
if (row == size) {
// at this point we've hit the end of the board
cout << "Solution: ";
for (int i = 0; i < size; i++) {
cout << board[i] << " ";
}
cout << endl;
return true;
}
else
{
for (int i = 0; i < size; i++)
{
if (okayPosition(row, i))
{
board[row] = i;
if(solveNQueens(row + 1)) return true;
}
}
}
return false;
}
int main(){
for(int i = 0; i < size; i++) {
board[i] = 0;
}
solveNQueens(0);
return 0;
}