1
1
#include <stdio.h>
2
- #define EMPTY '-'
3
- #define QUEEN 'Q'
2
+ #include <string.h>
4
3
5
- char queen [100 ][100 ];
6
- int n ;
4
+ #define EMPTY 0
5
+ #define QUEEN 1
6
+
7
+ int queen [100 ][100 ];
8
+ int n , total_solutions ;
7
9
8
10
void initializeBoard (int n )
9
11
{
10
- int i ,j ;
11
-
12
- for (i = 1 ;i <=n ;i ++ )
13
- {
14
- for (j = 1 ;j <=n ;j ++ )
15
- {
16
- queen [i ][j ] = EMPTY ;
17
- }
18
- }
12
+ memset (queen , EMPTY , sizeof (queen ));
19
13
}
20
14
21
15
void printBoard ()
@@ -26,24 +20,18 @@ void printBoard()
26
20
{
27
21
for (j = 1 ;j <=n ;j ++ )
28
22
{
29
- printf ("%c " , queen [i ][j ]);
23
+ printf ("%c " , queen [i ][j ] ? 'Q' : '-' );
30
24
}
31
25
printf ("\n" );
32
26
}
27
+ printf ("\n" );
33
28
}
34
29
35
30
int haveConflict (int row , int col )
36
31
{
37
32
int i ,j ;
38
33
39
- //check queen column
40
- for (i = 1 ;i <=n ;i ++ )
41
- {
42
- if (queen [row ][i ] == QUEEN )
43
- return 1 ;
44
- }
45
-
46
- //check queen row
34
+ //check the column positions above this position
47
35
for (i = 1 ;i < row ;i ++ )
48
36
{
49
37
if (queen [i ][col ] == QUEEN )
@@ -68,46 +56,41 @@ int haveConflict(int row, int col)
68
56
}
69
57
70
58
//target is to place one queen in each row so that no one collides with each other
71
- //Here placed_queen parameter shows how much queen we've already placed, also how much row we've already covvered
72
- void backtrack (int placed_queen )
59
+ //Here queen_row parameter shows the current we're going to place a Queen
60
+ void backtrack (int queen_row )
73
61
{
74
- int i , success = 0 ,next_move ;
75
- if (placed_queen > n ) return ; // All queens are placed properly
62
+ int i ;
76
63
77
- for ( i = 1 ; i <= n ; i ++ )
64
+ if ( queen_row > n )
78
65
{
79
- if (queen [placed_queen ][i ] == QUEEN ) //If we found already placed queen, remove it
80
- {
81
- //remove queen
82
- queen [placed_queen ][i ] = EMPTY ;
83
- continue ;
84
- }
66
+ total_solutions ++ ;
67
+ printBoard ();
68
+ return ;
69
+ }
85
70
86
- if (!haveConflict (placed_queen , i ))
71
+ for (i = 1 ;i <=n ;i ++ )
72
+ {
73
+ if (!haveConflict (queen_row , i ))
87
74
{
88
- //place a queen piece
89
- success = 1 ;
75
+ queen [queen_row ][i ] = QUEEN ;
90
76
91
- queen [ placed_queen ][ i ] = QUEEN ;
77
+ backtrack ( queen_row + 1 ) ;
92
78
93
- break ;
79
+ queen [ queen_row ][ i ] = EMPTY ;
94
80
}
95
81
}
96
-
97
- next_move = success ? (placed_queen + 1 ) : (placed_queen - 1 );
98
-
99
- backtrack (next_move );
100
82
}
101
83
102
84
int main ()
103
85
{
86
+ printf ("Enter Board size: " );
104
87
scanf ("%d" , & n );
105
88
106
89
initializeBoard (n );
107
90
108
- backtrack (0 );
91
+ backtrack (1 );
109
92
110
- printBoard ( );
93
+ printf ( "Total Solutions: %d\n" , total_solutions );
111
94
112
95
return 0 ;
113
96
}
0 commit comments