-
Notifications
You must be signed in to change notification settings - Fork 2
/
n_queen_combinations.c
71 lines (62 loc) · 1.15 KB
/
n_queen_combinations.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
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
#define MAX 10
int board[MAX];
int total_solution = 0;
void n_queen(int row);
void show_solution();
bool is_safe(int row, int col);
int n;
int main()
{
printf("N: "); scanf("%d",&n);
n_queen(1);
return 7;
}
void n_queen(int row)
{
register int col;
for(col=1; col<=n; col++)
{
if(is_safe(row, col))
{
board[row] = col;
if(row == n)
show_solution();
else
n_queen(row+1);
}
}
}
void show_solution()
{
total_solution++;
printf("Solution: %d\n", total_solution);
register int i,j;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
if(board[i] == j)
printf(" %c ",'Q');
else
printf(" %c ", '-');
}
puts("");
}
puts("\n\n");
}
bool is_safe(int row, int col)
{
register int i;
for(i=1; i<row; i++)
{
// diagonally check
if(abs(board[i]-col) == abs(i-row))
return false;
if(board[i] == col)
return false;
}
return true;
}