-
Notifications
You must be signed in to change notification settings - Fork 2
/
Nqueen.cpp
107 lines (86 loc) · 1.34 KB
/
Nqueen.cpp
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
#include <iostream>
using namespace std;
int place(int x[], int k)
{
for(int i=1; i<k; i++)
if(x[i] == x[k] || abs(x[i] - x[k]) == abs(i-k))
return 0;
return 1;
}
void printSolution(int n,int x[])
{
char c[10][10];
for(int i=1; i<=n; i++)
{
for(int j=1;j<=n;j++)
c[i][j]='X';
}
for(int i=1;i<=n;i++)
c[i][x[i]]='Q';
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout << c[i][j] << "\t";
}
cout << endl;
}
}
void Nqueen(int n)
{
int x[10], count=0, k=1;
x[k] = 0;
while(k)
{
x[k] = x[k] + 1;
while(x[k] <= n && !place(x,k))
{
x[k] = x[k] + 1;
}
if(x[k] <= n)
{
if( k == n)
{
count++;
cout << "Solution : " << count << endl;
printSolution(n,x);
}
else
{
k++;
x[k] = 0;
}
}
else
{
k--;
}
}
return;
}
int main()
{
int n;
cout << "Enter the number of queens: " << endl;
cin >> n;
Nqueen(n);
}
/*OUTPUT
Ashwani@Ashwanis-MacBook-Air algorithmslab (master) $ g++ Nqueen.cpp
Ashwani@Ashwanis-MacBook-Air algorithmslab (master) $ ./a.out
Enter the number of queens:
4
Solution : 1
X Q X X
X X X Q
Q X X X
X X Q X
Solution : 2
X X Q X
Q X X X
X X X Q
X Q X X
Ashwani@Ashwanis-MacBook-Air algorithmslab (master) $ git checkout -b add
Switched to a new branch 'add'
Ashwani@Ashwanis-MacBook-Air algorithmslab (add) $ git add Nqueen.cpp
*/