-
Notifications
You must be signed in to change notification settings - Fork 47
/
N-Queens.cpp
81 lines (72 loc) · 1.47 KB
/
N-Queens.cpp
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
#include <bits/stdc++.h>
using namespace std;
const int n = 15;
bool isSafe(int chess[n][n], int row, int col)
{
int i, j;
//Checking for the column(placing row-wise)
for(i = row-1 ; i >= 0; i--)
if(chess[i][col])
return false;
//Checking the primary diagonal
i = row;
j = col;
while(i >= 0 && j >= 0)
{
if(chess[i][j])
return false;
i--;
j--;
}
//Checking the other diagonal
i = row;
j = col;
while(i >=0 && j < n)
{
if(chess[i][j])
return false;
i--;
j++;
}
return true;
}
bool nQueen(int chess[n][n], int row)
{
if(row >= n)
return true;
for(int col = 0 ; col < n; col++)
{
if(isSafe(chess, row, col))
{
chess[row][col] = 1;
if(nQueen(chess, row+1))
return true;
chess[row][col] = 0;
}
}
return false;
}
int main()
{
int i, j;
int chess[n][n];
for(i = 0 ; i <n;i++)
{
for(j=0;j<n;j++)
chess[i][j] = 0;
}
if(nQueen(chess, 0))
{
for(i =0 ;i<n;i++)
{
for(j=0;j<n;j++)
cout << chess[i][j] << " ";
cout << endl;
}
}
else
{
cout << "Not possible";
}
return 0;
}