-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathN Queen Problem.cpp
More file actions
78 lines (76 loc) · 1.49 KB
/
N Queen Problem.cpp
File metadata and controls
78 lines (76 loc) · 1.49 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
#include<iostream>
using namespace std;
#define N 6
void Print(int matrix[N][N])
{
for (int i = 0; i <N; i++)
{
for (int j = 0; j <N; j++)
{
cout<<" "<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
bool queen(int matrix[N][N], int r, int c)
{
int i, j;
for (i = 0; i < c; i++)
{
if (matrix[r][i])
{
return false;
}
}
for (i = r, j = c; i >= 0 && j >= 0; i--, j--)
{
if (matrix[i][j])
{
return false;
}
}
for (i = r, j = c; j >= 0 && i <N; i++, j--)
{
if (matrix[i][j])
{
return false;
}
}
return true;
}
bool solve(int matrix[N][N], int c)
{
if (c>=N)
{
return true;
}
for (int i = 0; i <N; i++)
{
if (queen(matrix, i, c))
{
matrix[i][c] = 1;
if (solve(matrix, c + 1))
{
return true;
}
matrix[i][c] = 0;
}
}
return false;
}
int main()
{
int matrix[N][N] = { { 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 } };
if (solve(matrix, 0) == false)
{
cout<<"Solution does not exist";
return 0;
}
Print(matrix);
return 0;
}