1+ """
2+ @author:aaditkamat
3+ @date: 13/01/2019
4+ """
5+ def print_chessboard (chessboard ):
6+ for i in range (len (chessboard )):
7+ print (chessboard [i ])
8+
9+ def fill_chessboard (i , j ,chessboard ):
10+ chessboard [i ][j ] = 1
11+
12+ for x in range (len (chessboard )):
13+ if x != i :
14+ chessboard [x ][j ] = 0
15+
16+ for y in range (len (chessboard )):
17+ if y != j :
18+ chessboard [i ][y ] = 0
19+
20+ x , y = (i + 1 , j + 1 )
21+ while x < len (chessboard ) and y < len (chessboard ):
22+ chessboard [x ][y ] = 0
23+ x += 1
24+ y += 1
25+
26+ x , y = (i - 1 , j - 1 )
27+ while x >= 0 and y >= 0 :
28+ chessboard [x ][y ] = 0
29+ x -= 1
30+ y -= 1
31+
32+ x , y = (i + 1 , j - 1 )
33+ while x < len (chessboard ) and y >= 0 :
34+ chessboard [x ][y ] = 0
35+ x += 1
36+ y -= 1
37+
38+ x , y = (i - 1 , j + 1 )
39+ while x >= 0 and y < len (chessboard ):
40+ chessboard [x ][y ] = 0
41+ x -= 1
42+ y += 1
43+
44+ def try_position (i , chessboard ):
45+ fill_chessboard (0 , i , chessboard )
46+
47+ for i in range (1 , len (chessboard )):
48+ for j in range (len (chessboard )):
49+ if chessboard [i ][j ] == - 1 :
50+ fill_chessboard (i , j , chessboard )
51+
52+ def reset_chessboard (chessboard ):
53+ for i in range (len (chessboard )):
54+ for j in range (len (chessboard )):
55+ chessboard [i ][j ] = - 1
56+
57+ def is_correct (chessboard ):
58+ for i in range (len (chessboard )):
59+ if chessboard [i ].count (1 ) == 0 :
60+ return False
61+ return True
62+
63+ def n_queens (num ):
64+ chessboard = []
65+ for i in range (num ):
66+ chessboard .append ([- 1 ] * num )
67+
68+ for i in range (num ):
69+ try_position (i , chessboard )
70+ if (is_correct (chessboard )):
71+ print_chessboard (chessboard )
72+ return
73+ reset_chessboard (chessboard )
74+
75+ def main ():
76+ print ("Enter number of queens: " , end = "" )
77+ num = int (input ())
78+ n_queens (num )
79+
80+ main ()
0 commit comments