-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightQueens.py
More file actions
114 lines (88 loc) · 2.04 KB
/
EightQueens.py
File metadata and controls
114 lines (88 loc) · 2.04 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python
# coding: utf-8
# In[1]:
grid = [[0 for i in range(8)] for j in range(8)]
# In[2]:
def place(row,col,grid,val=1):
grid[row][col] = 99
for i in range(8):
if grid[i][col] != 99:
grid[i][col] = grid[i][col]+val
else:
continue
for j in range(8):
if grid[row][j] != 99:
grid[row][j] = grid[row][j]+val
else:
continue
# upper left
for i in range(1,7):
x = row - i
y = col - i
if x >= 0 and y >= 0:
grid[x][y] = grid[x][y]+val
else:
continue
# upper right
for i in range(1,7):
x = row + i
y = col - i
if x <= 7 and y >= 0:
grid[x][y] = grid[x][y]+val
else:
continue
# lower left
for i in range(1,7):
x = row - i
y = col + i
if x >= 0 and y <= 7:
grid[x][y] = grid[x][y]+val
else:
continue
# upper right
for i in range(1,7):
x = row + i
y = col + i
if x <= 7 and y <= 7:
grid[x][y] = grid[x][y]+val
else:
continue
if val != 1:
grid[row][col] = 0
return grid
# In[3]:
def gprint(grid):
for i in range(8):
for j in range(8):
if grid[i][j] == 99:
print("Q ",end='')
elif grid[i][j] == 0:
print(". ",end='')
else:
print("x ",end='')
print('\n')
print('\n')
# In[4]:
def possible(row,col,grid):
if grid[row][col] == 0:
return True
else:
return False
# In[5]:
grid = [[0 for i in range(8)] for j in range(8)]
count = 0
def solve(row):
global grid
global count
if row == 8:
count = count + 1
print(count)
gprint(grid)
return
for col in range(8):
if possible(row,col,grid):
place(row,col,grid,1)
solve(row+1)
place(row,col,grid,-1)
# In[6]:
solve(0)