File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Getting number of Queens
2
+ print ("Enter the number of Queens" )
3
+ N = int (input ())
4
+
5
+ # Chessboard
6
+ # NxN matrix with all the elements 0
7
+ chess_board = [[0 ]* N for _ in range (N )]
8
+
9
+ def is_attack (i , j ):
10
+ # Checking if there is a Queen in row or column
11
+ for k in range (0 ,N ):
12
+ if chess_board [i ][k ]== 1 or chess_board [k ][j ]== 1 :
13
+ return True
14
+ # Checking diagonals
15
+ for k in range (0 ,N ):
16
+ for l in range (0 ,N ):
17
+ if (k + l == i + j ) or (k - l == i - j ):
18
+ if chess_board [k ][l ]== 1 :
19
+ return True
20
+ return False
21
+
22
+ def N_queen (n ):
23
+ # If n is 0, solution found
24
+ if n == 0 :
25
+ return True
26
+ for i in range (0 ,N ):
27
+ for j in range (0 ,N ):
28
+ '''Checking if we can place a queen here or not
29
+ queen will not be placed if the place is being attacked
30
+ or already occupied'''
31
+ if (not (is_attack (i ,j ))) and (chess_board [i ][j ]!= 1 ):
32
+ chess_board [i ][j ] = 1
33
+ # Recursion
34
+ # Whether we can put the next Queen with this arrangment or not
35
+ if N_queen (n - 1 )== True :
36
+ return True
37
+ chess_board [i ][j ] = 0
38
+
39
+ return False
40
+
41
+ N_queen (N )
42
+ for i in chess_board :
43
+ print (i )
You can’t perform that action at this time.
0 commit comments