Skip to content

Commit 36a813e

Browse files
Merge pull request #578 from gauravburjwal/n-queens
added n-queens problem in python
2 parents 7eb7b3e + c55eaca commit 36a813e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

N-Queens/Python/n-queens.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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)

0 commit comments

Comments
 (0)