-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queen.c
112 lines (111 loc) · 1.76 KB
/
N-Queen.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//This program solves the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
#include<stdio.h>
#include<conio.h>
#define INF 9999
char board[20][20];
int n, count;
int getMarked(int row)
{
int i;
for(i=0;i<n;i++)
{
if(board[row][i] == 'Q')
{
return i;
}
}
return INF;
}
int feasible(int row, int col)
{
int i, tcol;
for(i=0;i<n;i++)
{
tcol = getMarked(i);
if(col==tcol || abs(row-i)==abs(col-tcol))
{
return 0;
}
}
return 1;
}
void printSolution()
{
int i, j;
printf("\n__Solution %d__\nCoordinates: ", count);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(board[i][j] == 'Q')
{
printf("(%d, %d)", i+1, j+1);
}
}
}
printf("\nBoard: __", count);
for(i=1;i<=n;i++)
{
printf("___");
}
printf("\n | ");
for(i=1;i<=n;i++)
{
printf(" %d ", i);
}
printf("|\n");
for(i=0;i<n;i++)
{
printf(" |%d ", i+1);
for(j=0;j<n;j++)
{
printf(" %c ", board[i][j]);
}
printf("|\n");
}
printf(" ‾‾");
for(i=1;i<=n;i++)
{
printf("‾‾‾‾");
}
printf("\n");
getch();
}
void nQueens(int row)
{
int i;
if(row<n)
{
for(i=0;i<n;i++)
{
if(feasible(row,i))
{
board[row][i] = 'Q';
nQueens(row+1);
board[row][i] = '-';
}
}
}
else
{
count++;
printSolution();
}
}
void main()
{
int i, j;
clrscr();
printf("No of Queen (N) = ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
board[i][j] = '-';
}
}
nQueens(0);
printf("\nTotal Solutions: %d", count);
getch();
}