2019-06-23_the-eight-queens.html


001| #:name::The Eight Queens
002| #:link::https://thehardcorecoder.com/2019/06/23/the-eight-queens/
003| #:date::2019-06-23
004| #:code::
005| class chessboard (object):
006|     '''Chessboard class.'''
007|     def __init__ (self, nrows=8, ncols=8):
008|         self.nr = nrows
009|         self.nc = ncols
010|         a = [0 for cx in range(ncols)]
011|         self.board = [list(a) for rx in range(nrows)]
012| 
013|     def row (self, row):
014|         '''Get a row of the board.'''
015|         if 0 <= row < self.nr:
016|             return self.board[row]
017|         return []
018| 
019|     def col (self, col):
020|         '''Get a column of the board.'''
021|         if 0 <= col < self.nc:
022|             return [b[col] for b in self.board]
023|         return []
024| 
025|     def __getitem__ (self, row_col):
026|         '''Get a board square.'''
027|         row,col = row_col
028|         if 0 <= row < self.nr:
029|             if 0 <= col < self.nc:
030|                 return self.board[row][col]
031|         return 0
032| 
033|     def __setitem__ (self, row_col, value):
034|         '''Set a board square.'''
035|         row,col = row_col
036|         if 0 <= row < self.nr:
037|             if 0 <= col < self.nc:
038|                 self.board[row][col] = value
039| 
040|     def __str__ (self):
041|         a = ['%s\n' % row for row in self.board]
042|         return ''.join(a)
043| 
044| #:code::
045| def find_queens_1 (board, col=0, NR=8, NC=8, fp=stdout):
046|     '''The Eight Queens. Solution 1.'''
047| 
048|     # For each possible row in this column...
049|     for row in range(NR):
050|         # SPECIAL: Don't bother with obvious reflections...
051|         if (col==0) and ((NR//2) <= row):
052|             break
053| 
054|         # Place a queen...
055|         board[row,col] = QUEEN
056|         # Test the board...
057|         if check_board_layout(board, NR,NC):
058|             # If this is the last column...
059|             if col == (NC-1):
060|                 # Then eight queens are successfully placed...
061|                 record_board_position(board, NR,NC, fp)
062|             else:
063|                 # RECURSE (otherwise keep going)...
064|                 find_queens_1(board, col+1, NR,NC, fp)
065| 
066|         # Remove the placed queen...
067|         board[row,col] = 0
068| 
069| #:code::
070| def check_board_layout (board, NR, NC):
071|     # Check rows...
072|     for rx in range(NR):
073|         cells = board.row(rx)
074|         if QUEEN < sum(cells): return False
075| 
076|     # Check cols...
077|     for cx in range(NC):
078|         cells = board.col(cx)
079|         if QUEEN < sum(cells): return False
080| 
081|     # Check diagonals...
082|     for rx in range(NR-1):
083|         cells = [board[rx+cx, cx] for cx in range(NC-rx)]
084|         if QUEEN < sum(cells): return False
085|         cells = [board[rx+cx, NC-cx-1] for cx in range(NC-rx)]
086|         if QUEEN < sum(cells): return False
087| 
088|     for cx in range(1, NC-1):
089|         cells = [board[rx, cx+rx] for rx in range(NR-cx)]
090|         if QUEEN < sum(cells): return False
091|         cells = [board[rx, NR-(cx+rx)-1] for rx in range(NR-cx)]
092|         if QUEEN < sum(cells): return False
093| 
094|     # No collisions!
095|     return True
096| 
097| #:code::
098| def find_queens_2 (board, col=0, NR=8, NC=8, fp=stdout):
099|     '''The Eight Queens. Solution 2.'''
100| 
101|     # For each possible row in this column...
102|     for row in range(NR):
103|         # Don't bother with obvious reflections...
104|         if (col==0) and ((NR//2) <= row):
105|             break
106| 
107|         # Place a queen...
108|         if check_queen_position(board, row,col, NR,NC):
109|             board[row,col] = QUEEN
110| 
111|             # If this is the last column...
112|             if col == (NC-1):
113|                 # ...then eight queens are successfully placed...
114|                 record_board_position(board, NR,NC, fp)
115|             else:
116|                 # RECURSE (otherwise keep going)...
117|                 find_queens_2(board, col+1, NR,NC, fp)
118| 
119|             # Remove the placed queen...
120|             board[row,col] = 0
121| 
122| #:code::
123| def check_queen_position (board, row,col, NR,NC):
124|     '''Check for a valid position for the Queen.'''
125| 
126|     for ix in range(max(NR,NC)):
127|         rx0, rx1 = row-ix, row+ix
128|         cx0, cx1 = col-ix, col+ix
129| 
130|         if board[row,cx0] == QUEEN: return False
131|         if board[row,cx1] == QUEEN: return False
132|         if board[rx0,col] == QUEEN: return False
133|         if board[rx1,col] == QUEEN: return False
134|         if board[rx0,cx0] == QUEEN: return False
135|         if board[rx0,cx1] == QUEEN: return False
136|         if board[rx1,cx0] == QUEEN: return False
137|         if board[rx1,cx1] == QUEEN: return False
138| 
139|     return True
140| 
141| #:code::
142| def find_queens_3 (board, col=0, NR=8, NC=8, fp=stdout):
143|     '''The Eight Queens. Solution 3.'''
144| 
145|     # For each possible row in this column...
146|     for row in range(NR):
147|         # Don't bother with obvious reflections...
148|         if (col==0) and ((NR//2) <= row):
149|             break
150| 
151|         # Place a queen...
152|         if add_queen_to_board(board, row,col, NR,NC):
153|             # If this is the last column...
154|             if col == (NC-1):
155|                 # ...then eight queens are successfully placed...
156|                 record_board_position(board, NR,NC, fp)
157|             else:
158|                 # RECURSE (otherwise keep going)...
159|                 find_queens_3(board, col+1, NR,NC, fp)
160|             # Remove the placed queen...
161|             remove_queen_from_board(board, row,col, NR,NC)
162| 
163| #:code::
164| def add_queen_to_board (board, row,col, NR,NC):
165|     '''Add a Queen to the board.'''
166|     if board[row,col]:
167|         return False
168| 
169|     board[row,col] = QUEEN
170| 
171|     for ix in range(1,max(NR,NC)):
172|         rx0, rx1 = row-ix, row+ix
173|         cx0, cx1 = col-ix, col+ix
174|         mask = 1 << col
175|         board[row,cx0] |= mask
176|         board[row,cx1] |= mask
177|         board[rx0,col] |= mask
178|         board[rx1,col] |= mask
179|         board[rx0,cx0] |= mask
180|         board[rx0,cx1] |= mask
181|         board[rx1,cx0] |= mask
182|         board[rx1,cx1] |= mask
183| 
184|     return True
185| 
186| def remove_queen_from_board (board, row,col, NR,NC):
187|     '''Remove a Queen from the board.'''
188| 
189|     board[row,col] = 0
190| 
191|     for ix in range(1,max(NR,NC)):
192|         rx0, rx1 = row-ix, row+ix
193|         cx0, cx1 = col-ix, col+ix
194|         mask = ~(1 << col)
195|         board[row,cx0] &= mask
196|         board[row,cx1] &= mask
197|         board[rx0,col] &= mask
198|         board[rx1,col] &= mask
199|         board[rx0,cx0] &= mask
200|         board[rx0,cx1] &= mask
201|         board[rx1,cx0] &= mask
202|         board[rx1,cx1] &= mask
203| 
204| #:code::
205| def record_board_position (board, NR,NC, fp):
206|     '''Write current board to an output stream.'''
207|     fp.flush()
208| 
209|     divider = ' +%s \n' % ('---+'*NC)
210|     fp.write(divider)
211| 
212|     # For each row on the board...
213|     for rx in range(NR):
214|         fp.write(' |')
215| 
216|         # For each column in the row...
217|         for cx in range(NC):
218|             s = ' Q |' if board[rx,cx] == QUEEN else ' |'
219| 
220|             # Write the cell contents...
221|             fp.write(s)
222| 
223|         # End of row...
224|         fp.write('\n')
225|         fp.write(divider)
226| 
227|     # End of board...
228|     fp.write('\n')
229|     fp.flush()
230| 
231| #:code::
232| def find_queens_4 (accum=[], NR=8, NC=8, fp=stdout):
233|     '''The Eight Queens. Solution 4.'''
234| 
235|     # For each row (1-8)...
236|     for row in [r+1 for r in range(NR)]:
237|         # Special test to avoid reflected solutions...
238|         if (len(accum) == 0) and (int((NR+1)/2) < row):
239|             break
240| 
241|         # If row is available...
242|         if check_row(accum, row, NR,NC):
243|             # Add it...
244|             accum.append(row)
245| 
246|             # If we added all the rows...
247|             if len(accum) == NC:
248|                 # We found a solution. Report and continue...
249|                 report_solution(accum, NR,NC, fp)
250|             else:
251|                 ### RECURSE! ###
252|                 find_queens_4(accum, NR,NC, fp)
253| 
254|             # Done trying, remove...
255|             accum.pop()
256| 
257| #:code::
258| def check_row (accum, row, NR, NC):
259|     '''Check row for availability.'''
260|     # Test for row already occupied...
261|     if row in accum:
262|         return False # collision!
263| 
264|     # Test for (upper) diagonal already occupied...
265|     for ix,ch in enumerate(reversed(accum)):
266|         n = row + (ix + 1)
267|         if NR < n: break
268|         if n == ch:
269|             return False # collision!
270| 
271|     # Test for (lower) diagonal already occupied...
272|     for ix,ch in enumerate(reversed(accum)):
273|         n = row - (ix + 1)
274|         if n < 1: break
275|         if n == ch:
276|             return False # collision!
277| 
278|     # Queen can be placed...
279|     return True
280| 
281| #:code::
282| def report_solution (accum, NR, NC, fp):
283|     '''Write current board to an output stream.'''
284|     fp.flush()
285| 
286|     # numerical value...
287|     fp.write(' %s:\n' % accum)
288|     divider = ' +%s \n' % ('---+'*NC)
289|     fp.write(divider)
290| 
291|     for rx in range(NR):
292|         row = rx + 1
293| 
294|         # Row...
295|         fp.write(' |')
296|         for cx in range(NC):
297|             s = ' Q |' if accum[cx] == row else ' |'
298|             fp.write(s)
299| 
300|         # End of row...
301|         fp.write('\n')
302|         fp.write(divider)
303| 
304|     # End of board...
305|     fp.write('\n')
306|     fp.flush()
307| 
308| #:code::
309| 
310| #:code::
311| 
312| #:code::
313| 
314| #:end:code::
315|