-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.cpp
More file actions
68 lines (68 loc) · 1.19 KB
/
NQueen.cpp
File metadata and controls
68 lines (68 loc) · 1.19 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
#include <iostream>
using namespace std;
bool canPlace(int board[][20], int n, int x, int y)
{
for (int k = 0; k < x; k++)
{
if (board[k][y] == 1)
return false;
}
int i = x;
int j = y;
while (i >= 0 && j >= 0)
{
if (board[i][j] == 1)
return false;
i--;
j--;
}
i = x;
j = y;
while (i >= 0 && j < n)
{
if (board[i][j] == 1)
return false;
i--;
j++;
}
return true;
}
void printBoard(int board[][20], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
int solveNQueen(int board[][20], int n, int i)
{
if (i == n)
{
printBoard(board, n);
return 1;
}
int ways = 0;
for (int j = 0; j < n; j++)
{
if (canPlace(board, n, i, j))
{
board[i][j] = 1;
ways += solveNQueen(board, n, i + 1);
board[i][j] = 0;
}
}
return ways;
}
int main()
{
int board[20][20] = {0};
int n, i;
cin >> n;
solveNQueen(board, n, 0);
return 0;
}