Skip to content

Commit 8f9f802

Browse files
nqueen challenge.py
1 parent b3b041b commit 8f9f802

File tree

1 file changed

+62
-33
lines changed

1 file changed

+62
-33
lines changed

nqueen challenge.py

+62-33
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,69 @@
1+
2+
13
global N
24
N = 4
5+
36
def printSolution(board):
4-
for i in range(N):
5-
for j in range(N):
6-
print (board[i][j],end=' ')
7-
print()
7+
for i in range(N):
8+
for j in range(N):
9+
print (board[i][j],end=' ')
10+
print()
11+
12+
13+
814
def isSafe(board, row, col):
9-
for i in range(col):
10-
if board[row][i] == 1:
11-
return False
12-
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
13-
if board[i][j] == 1:
14-
return False
15-
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
16-
if board[i][j] == 1:
17-
return False
18-
return True
15+
16+
for i in range(col):
17+
if board[row][i] == 1:
18+
return False
19+
20+
21+
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
22+
if board[i][j] == 1:
23+
return False
24+
25+
26+
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
27+
if board[i][j] == 1:
28+
return False
29+
30+
return True
31+
1932
def solveNQUtil(board, col):
20-
if col >= N:
21-
return True
22-
for i in range(N):
23-
if isSafe(board, i, col):
24-
board[i][col] = 1
25-
if solveNQUtil(board, col + 1) == True:
26-
return True
27-
board[i][col] = 0
28-
return False
33+
if col >= N:
34+
return True
35+
36+
37+
for i in range(N):
38+
39+
if isSafe(board, i, col):
40+
41+
board[i][col] = 1
42+
43+
if solveNQUtil(board, col + 1) == True:
44+
return True
45+
46+
47+
board[i][col] = 0
48+
49+
50+
return False
51+
2952
def solveNQ():
30-
board = [[0, 0, 0, 0],
31-
[0, 0, 0, 0],
32-
[0, 0, 0, 0],
33-
[0, 0, 0, 0]
34-
]
35-
if solveNQUtil(board, 0) == False:
36-
print ("Solution does not exist")
37-
return False
38-
printSolution(board)
39-
return True
53+
board = [ [0, 0, 0, 0],
54+
[0, 0, 0, 0],
55+
[0, 0, 0, 0],
56+
[0, 0, 0, 0]
57+
]
58+
59+
if solveNQUtil(board, 0) == False:
60+
print ("Solution does not exist")
61+
return False
62+
63+
printSolution(board)
64+
return True
65+
66+
4067
solveNQ()
68+
69+

0 commit comments

Comments
 (0)