1
- #define N 4
1
+ #define N 12
2
2
#include < stdio.h>
3
3
#include < stdbool.h>
4
4
5
5
6
+ void printSolution (int board[N][N]){
7
+ for (int i = 0 ; i < N; i++){
8
+ for (int j = 0 ; j < N; j++){
9
+ if (board[i][j]) printf (" Q " );
10
+ else printf (" . " );
11
+ }
12
+ printf (" \n " );
13
+ }
14
+ }
15
+
16
+ bool isSafe (int board[N][N], int row, int col){
17
+
18
+ int i, j;
19
+
20
+ // checking left since the queen is already placed (no need to check the right side)
21
+ for (i = 0 ; i < col; i++) if (board[row][i]) return false ;
22
+
23
+
24
+ // check the upper diagonal
25
+ for (i = row, j = col; i >= 0 && j >= 0 ; i--, j--) if (board[i][j]) return false ;
26
+
27
+
28
+ // check the lower diagonal
29
+ for (i = row, j = col; j >= 0 && i < N ; i++, j--) if (board[i][j]) return false ;
30
+
31
+
32
+ return true ;
33
+
34
+ }
35
+
6
36
bool solveNQUtil (int board[N][N], int col){
7
37
8
38
if (col >= N) return true ;
39
+
40
+ for (int i = 0 ; i < N; i++){
41
+ if (isSafe (board, i, col)){
42
+
43
+ board[i][col] = 1 ;
44
+
45
+ if (solveNQUtil (board, col+1 )) return true ;
46
+
47
+ // backtrack to 0
48
+ board[i][col] = 0 ;
49
+ }
50
+ }
9
51
10
52
return false ;
11
53
}
@@ -14,12 +56,26 @@ bool solveNQUtil(int board[N][N], int col){
14
56
bool solveNQ (){
15
57
16
58
int board[N][N] = {
17
- {0 , 0 , 0 , 0 ,},
18
- {0 , 0 , 0 , 0 ,},
19
- {0 , 0 , 0 , 0 ,},
20
- {0 , 0 , 0 , 0 ,}
59
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
60
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
61
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
62
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
63
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
64
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
65
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
66
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
67
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
68
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
69
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },
70
+ {0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
21
71
};
22
72
73
+ if (solveNQUtil (board, 0 ) == false ){
74
+ printf (" No solution possible" );
75
+ return false ;
76
+ }
77
+
78
+ printSolution (board);
23
79
return true ;
24
80
25
81
}
0 commit comments