- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEightQueen.py
More file actions
Latest commit
98 lines (83 loc) · 2.58 KB
/
Copy pathEightQueen.py
File metadata and controls
98 lines (83 loc) · 2.58 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
#!/usr/bin/env python
# placeing n queens on n*n chessboard on two queens attack each other
# the solution requires that no two queens share the same row, column, or diagonal
importBoard
importunittest
classQueenBoard(Board.Board):
def__init__(self, num_queens=8):
super(QueenBoard,self).__init__(
num_rows=num_queens, num_cols=num_queens, init_char=' ')
@property
defnum_queens(self):
returnself.num_rows
defplaced(self, point):
'''
Determine whetheer the queen can be put on this space
Args:
point: row and column position on the chess board
Returns:
True if a queen can be placed on that position.
'''
ifnotself.valid(point):
returnFalse
# whether there are queens in the same row, column and diagonal
# get all the position for the queens
forrowinrange(self.num_rows):
forcolinrange(self.num_cols):
ifself[Board.Point(row, col)] !='Q':
continue
if (row==point.roworcol==point.color
abs(row-point.row) ==abs(col-point.col)):
returnFalse
returnTrue
defsolver(self, col=0, solutions=None):
'''
Solve the n queeen problem
Looping throught the rows
Args:
col: Which column we are looking to place a queen in.
solutions: An optional array to collect solutions in.
If not given, only the first solution will be returned.
If given, all solutions will be put into this array.
Return:
list of all the solution
'''
# if n == 0:
# return [[]]
# prev = self.solver(n-1)
# solutions = []
# for sol in prev:
# for col in range(self.num_cols):
# current = Board.Point(n, col)
# if self.placed(current):
# solutions.append(sol + [current])
# return solutions
ifcol==self.num_rows:
print"Solved!"
ifsolutionsisnotNone:
solutions.append(str(self))
returnFalse
else:
printself
returnTrue
forrowinrange(self.num_rows):
current=Board.Point(row, col)
ifself.placed(current):
self[current] ='Q'
ifself.solver(col=col+1, solutions=solutions):
returnTrue
else:
self[current] =' '
returnFalse
defmain():
q=QueenBoard(8)
# pos = Point(2,3)
solutions= []
printq.solver(solutions=solutions)
print"Got %d solutions:"%len(solutions)
forsolutioninsolutions:
printsolution
# for qu in q.posQueens:
# print qu
if__name__=="__main__":
main()