-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8queen.py
46 lines (40 loc) · 864 Bytes
/
8queen.py
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
39
40
41
42
43
44
45
46
#load data from JSON
import json
inf = open("8queen.json")
board = json.loads(inf.read())
board = board["matrix"]
#display initial board configuration
for i in board:
print i
#check if the postion is safe (not attacked by a queen)
def isSafe(row, col):
for i in range(8):
for j in range(8):
if board[i][j] == 1:
if row == i:
return False
if col == j:
return False
if abs(row-i) == abs(col-j):
return False
return True
#recursively place queens if safe
def placeQueen(col):
if col >= 8:
print "Scanned all columns."
return True
for i in range(8):
if isSafe(i, col):
board[i][col] = 1
if placeQueen(col+1):
return True
board[i][col] = 0
return False
#start with first column
if placeQueen(1):
print "Solution found!"
else:
print "Solution not found!"
#display the final board
for i in board:
print i