1
+ #include <stdio.h>
2
+ // #define BOARD_SIZE 5
3
+ int n ;
4
+
5
+ void input (){
6
+ printf ("Enter the value of n: " );
7
+ scanf ("%d" , & n );
8
+ }
9
+ void displayChess (int chBoard [n ][n ]) {
10
+ for (int row = 0 ; row < n ; row ++ ) {
11
+ for (int col = 0 ; col < n ; col ++ )
12
+ printf ("%d " , chBoard [row ][col ]);
13
+ printf ("\n" );
14
+ }
15
+ }
16
+ int isQueenPlaceValid (int chBoard [n ][n ], int crntRow , int crntCol ) {
17
+ // checking if queen is in the left or not
18
+ for (int i = 0 ; i < crntCol ; i ++ )
19
+ if (chBoard [crntRow ][i ])
20
+ return 0 ;
21
+ for (int i = crntRow , j = crntCol ; i >= 0 && j >= 0 ; i -- , j -- )
22
+ //checking if queen is in the left upper diagonal or not
23
+ if (chBoard [i ][j ])
24
+ return 0 ;
25
+ for (int i = crntRow , j = crntCol ; j >= 0 && i < n ; i ++ , j -- )
26
+ //checking if queen is in the left lower diagonal or not
27
+ if (chBoard [i ][j ])
28
+ return 0 ;
29
+ return 1 ;
30
+ }
31
+ int solveProblem (int chBoard [n ][n ], int crntCol ) {
32
+ //when N queens are placed successfully
33
+ if (crntCol >= n )
34
+ return 1 ;
35
+ // checking placement of queen is possible or not
36
+ for (int i = 0 ; i < n ; i ++ ) {
37
+ if (isQueenPlaceValid (chBoard , i , crntCol )) {
38
+ //if validate, place the queen at place (i, col)
39
+ chBoard [i ][crntCol ] = 1 ;
40
+ //Go for the other columns recursively
41
+ if (solveProblem (chBoard , crntCol + 1 ))
42
+ return 1 ;
43
+ //When no place is vacant remove that queen
44
+ chBoard [i ][crntCol ] = 0 ;
45
+ }
46
+ }
47
+ return 0 ;
48
+ }
49
+ int displaySolution () {
50
+ int chBoard [n ][n ];
51
+ for (int i = 0 ; i < n ; i ++ )
52
+ for (int j = 0 ; j < n ; j ++ )
53
+ //set all elements to 0
54
+ chBoard [i ][j ] = 0 ;
55
+ //starting from 0th column
56
+ if (solveProblem (chBoard , 0 ) == 0 ) {
57
+ printf ("Solution does not exist" );
58
+ return 0 ;
59
+ }
60
+ displayChess (chBoard );
61
+ return 1 ;
62
+ }
63
+ int main () {
64
+ input ();
65
+ displaySolution ();
66
+ return 0 ;
67
+ }
0 commit comments