forked from imabhinav-am/Competetive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNqueenProblem.cpp
More file actions
66 lines (56 loc) · 952 Bytes
/
Copy pathNqueenProblem.cpp
File metadata and controls
66 lines (56 loc) · 952 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
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
using namespace std;
void print(int board[4][4])
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
}
bool issafe(int board[4][4],int row,int col)
{
for(int i=0;i<col;i++)
if(board[row][i])
return false;
for(int i=row,j=col;i>=0 && j>=0 ;i--,j--)
if(board[i][j])
return false;
for(int i=row,j=col;i<4 && j>=0 ;i++,j--)
if(board[i][j])
return false;
return true;
}
bool solve(int board[4][4],int col)
{
if(col==4)
return true;
for(int i=0;i<4;i++)
{
if(issafe(board,i,col))
{
board[i][col]=1;
if(solve(board,col+1))
return true;
board[i][col]=0;
}
}
return false;
}
int main()
{
int board[4][4] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if ( solve(board, 0) == false )
{
printf("SOLUTION DOES NOT EXIT");
return 0;
}
else
print(board);
return 0;
}