File tree Expand file tree Collapse file tree 1 file changed +108
-0
lines changed Expand file tree Collapse file tree 1 file changed +108
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* N-Queen Problem
2
+
3
+
4
+ You have to place n queens on an nxn chessboard.
5
+ Idea: Try all the possible positions for the queen. isSafe functions check whether
6
+ the current position is safe or not
7
+
8
+ */
9
+
10
+ #include < iostream>
11
+ using namespace std ;
12
+
13
+
14
+ bool isSafe (int board[][10 ], int i, int j, int n){
15
+ // Check in col
16
+
17
+ for (int row=0 ;row<i;row++){
18
+ if (board[row][j] == 1 ){
19
+ return false ;
20
+ }
21
+ }
22
+ // Left diagonal
23
+ int x=i;
24
+ int y=j;
25
+
26
+ while (x>=0 && y>=0 ){
27
+ if (board[x][y]==1 ){
28
+ return false ;
29
+ }
30
+ x--;
31
+ y--;
32
+ }
33
+ // Right diagonal
34
+ x=i;
35
+ y=j;
36
+
37
+ while (x>=0 && y>=0 ){
38
+ if (board[x][y]==1 ){
39
+ return false ;
40
+ }
41
+ x--;
42
+ y++;
43
+ }
44
+ // The position is safe
45
+ return true ;
46
+
47
+
48
+ }
49
+
50
+ bool nQueen (int board[][10 ], int i,int n){
51
+ if (i==n){// base case
52
+ // Place Queeen in n rows (0..n-1)
53
+ // print the board
54
+ for (int i=0 ;i<n;i++){
55
+ for (int j=0 ;j<n;j++){
56
+ if (board[i][j]==1 ){
57
+ cout<<" Q " ;
58
+ }
59
+ else {
60
+ cout<<" _ " ;
61
+ }
62
+ }
63
+ cout<<endl;
64
+ }
65
+ return true ;
66
+ }
67
+ // Recursive case
68
+
69
+ for (int j=0 ;j<n;j++){
70
+ // Check i,j th position is safe to place the queen or not.
71
+ if (isSafe (board,i,j,n)){
72
+ // Place the Queen ,i, j in the right position
73
+ board[i][j]=1 ;
74
+
75
+ if (nQueen (board,i+1 ,n)){
76
+ return true ;
77
+ }
78
+ // Means i,j is not the right position
79
+ board[i][j]=0 ; // backtracking
80
+ }
81
+ }
82
+ // coudln't place the queen in current position.
83
+ return false ;
84
+ }
85
+
86
+
87
+ int main (){
88
+ int n;
89
+ cin>>n;
90
+
91
+ int board[10 ][10 ]={0 };
92
+ nQueen (board,0 ,n);
93
+
94
+ return 0 ;
95
+
96
+ }
97
+
98
+ /* Input:
99
+ 4
100
+
101
+ Output:
102
+
103
+ _ Q _ _
104
+ _ _ _ Q
105
+ Q _ _ _
106
+ _ _ Q _
107
+
108
+ */
You can’t perform that action at this time.
0 commit comments