-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8q.py
More file actions
38 lines (34 loc) · 963 Bytes
/
Copy path8q.py
File metadata and controls
38 lines (34 loc) · 963 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import json
inf=open("8q.json")
board=json.loads(inf.read())
board=board["matrix"]
for i in board:
print(i)
def issafe(row,col):
for i in range(8):
for j in range(8):
if(board[i][j]==1): #if a queen exists here, then check if it attacks our queen
if(row==i):
return False
if(col==j):
return False
if(abs(row-i)==abs(col-j)):
return False
return True
def place(col):
if(col>=8): #if all 8 queens are placed, then finish
print("\t\tCompleted...")
return True
for i in range(8): #checking for all rows in that column
if(issafe(i,col)): #is it safe?
board[i][col]=1 #queen is placed here
if(place(col+1)==True): #recursive call to place next queen
return True
board[i][col]=0 #if not placed, then backtrack, i.e it sets to zero and the loop iterates to check for next position
return False
if(place(1)==True):
print("solution found")
else:
print("Solution not possible")
for i in board:
print(i)