Skip to content

Commit 15dcda1

Browse files
N-Queens
1 parent eee5bf3 commit 15dcda1

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Maths/N-queens.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Function to check is it safe to place queen at board[row][col]
2+
def isSafe(mat, row, col):
3+
n = len(mat)
4+
5+
# check this col on upperSide
6+
for i in range(row):
7+
if mat[i][col]:
8+
return False
9+
10+
# check upper diagonal on left side
11+
for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)):
12+
if mat[i][j]:
13+
return False
14+
15+
# check upper diagnoal on right side
16+
for i, j in zip(range(row-1, -1, -1), range(col+1, n)):
17+
if mat[i][j]:
18+
return False
19+
20+
return True
21+
22+
def placedQueen(row, mat):
23+
n = len(mat)
24+
25+
# If all queens are placed return True
26+
if row == n:
27+
return True
28+
29+
# consider the row and try placing queen in all columns one by one
30+
for i in range(n):
31+
# check if queen can be placed
32+
if isSafe(mat, row, i):
33+
mat[row][i] = 1
34+
if placedQueen(row+1, mat):
35+
return True
36+
mat[row][i] = 0
37+
38+
return False
39+
40+
# Function to find the solution to N-Queens problem
41+
def nQueens(n):
42+
# Intialise the board
43+
mat = [[0 for _ in range(n)] for _ in range(n)]
44+
45+
# If the solution exist
46+
if placedQueen(0, mat):
47+
# to store column of the queens
48+
ans = []
49+
for i in range(n):
50+
for j in range(n):
51+
if mat[i][j]:
52+
ans.append(j+1)
53+
return ans
54+
else:
55+
return [-1]
56+
57+
if __name__=="__main__":
58+
n = 4
59+
ans = nQueens(n)
60+
print(" ".join(map(str, ans)))

0 commit comments

Comments
 (0)