-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueeen-Backtracking.c
82 lines (67 loc) · 1019 Bytes
/
NQueeen-Backtracking.c
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
#include<stdio.h>
#include<stdbool.h>
int N =8;
int board[8][8] =
{
{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,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,0,0,0,0}
};
bool is_safe(int row, int col)
{
for(int i = 0;i<col;i++)
{
if(board[row][i] == 1)
return false;
}
int m,n;
for(m =row, n = col; m >= 0 && n >= 0 ; m--,n--)
{
if(board[m][n]== 1)
return false;
}
int a,b;
for(a = row, b = col; a<8 && b>=0 ; a++, b--)
{
if(board[a][b] == 1)
return false;
}
return true;
}
bool solve_queen( int col)
{
if(col>=8)
return true;
for(int i = 0; i<8; i++)
{
if(is_safe(i,col) == true)
{
board[i][col] = 1;
if(solve_queen( col+1) == true)
return true;
board[i][col] = 0;
}
}
return false;
}
int main()
{
if(solve_queen(0) == true)
{printf("Solution exist\n");
for(int i =0; i<8;i++)
{
for(int j =0;j<8;j++)
{printf("%d\t",board[i][j]);
}
printf("\n");
}
}
else
printf("Fail");
return 0;
}