File tree Expand file tree Collapse file tree 1 file changed +113
-0
lines changed
Backtracking/N-Queen Problem Expand file tree Collapse file tree 1 file changed +113
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include <stdio.h>
2
+ #define EMPTY '-'
3
+ #define QUEEN 'Q'
4
+
5
+ char queen [100 ][100 ];
6
+ int n ;
7
+
8
+ void initializeBoard (int n )
9
+ {
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
+ }
19
+ }
20
+
21
+ void printBoard ()
22
+ {
23
+ int i ,j ;
24
+
25
+ for (i = 1 ;i <=n ;i ++ )
26
+ {
27
+ for (j = 1 ;j <=n ;j ++ )
28
+ {
29
+ printf ("%c " , queen [i ][j ]);
30
+ }
31
+ printf ("\n" );
32
+ }
33
+ }
34
+
35
+ int haveConflict (int row , int col )
36
+ {
37
+ int i ,j ;
38
+
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
47
+ for (i = 1 ;i < row ;i ++ )
48
+ {
49
+ if (queen [i ][col ] == QUEEN )
50
+ return 1 ;
51
+ }
52
+
53
+ //check upper left diagonal
54
+ for (i = row - 1 ,j = col - 1 ;i > 0 && j > 0 ;i -- ,j -- )
55
+ {
56
+ if (queen [i ][j ] == QUEEN )
57
+ return 1 ;
58
+ }
59
+
60
+ //check upper right diagonal
61
+ for (i = row - 1 ,j = col + 1 ;i > 0 && j <=n ;i -- ,j ++ )
62
+ {
63
+ if (queen [i ][j ] == QUEEN )
64
+ return 1 ;
65
+ }
66
+
67
+ return 0 ;
68
+ }
69
+
70
+ //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 )
73
+ {
74
+ int i , success = 0 ,next_move ;
75
+ if (placed_queen > n ) return ; // All queens are placed properly
76
+
77
+ for (i = 1 ;i <=n ;i ++ )
78
+ {
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
+ }
85
+
86
+ if (!haveConflict (placed_queen , i ))
87
+ {
88
+ //place a queen piece
89
+ success = 1 ;
90
+
91
+ queen [placed_queen ][i ] = QUEEN ;
92
+
93
+ break ;
94
+ }
95
+ }
96
+
97
+ next_move = success ? (placed_queen + 1 ) : (placed_queen - 1 );
98
+
99
+ backtrack (next_move );
100
+ }
101
+
102
+ int main ()
103
+ {
104
+ scanf ("%d" , & n );
105
+
106
+ initializeBoard (n );
107
+
108
+ backtrack (0 );
109
+
110
+ printBoard ();
111
+
112
+ return 0 ;
113
+ }
You can’t perform that action at this time.
0 commit comments