|
| 1 | +r""" |
| 2 | +Problem: |
| 3 | +The n queens problem is of placing N queens on a N * N chess board such that |
| 4 | +no queen can attack any other queens placed on that chess board. This means |
| 5 | +that one queen cannot have any other queen on its horizontal, vertical and |
| 6 | +diagonal lines. |
| 7 | +""" |
| 8 | + |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +def depth_first_search( |
| 13 | + possible_board: List[int], |
| 14 | + diagonal_right_collisions: List[int], |
| 15 | + diagonal_left_collisions: List[int], |
| 16 | + boards: List[List[str]], |
| 17 | + n: int, |
| 18 | +) -> None: |
| 19 | + """ |
| 20 | + >>> boards = [] |
| 21 | + >>> depth_first_search([], [], [], boards, 4) |
| 22 | + >>> for board in boards: |
| 23 | + ... print(board) |
| 24 | + ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] |
| 25 | + ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . '] |
| 26 | + """ |
| 27 | + |
| 28 | + row = len(possible_board) |
| 29 | + |
| 30 | + if row == n: |
| 31 | + possible_board = [". " * i + "Q " + ". " * (n - 1 - i) |
| 32 | + for i in possible_board] |
| 33 | + boards.append(possible_board) |
| 34 | + return |
| 35 | + |
| 36 | + for col in range(n): |
| 37 | + |
| 38 | + if ( |
| 39 | + col in possible_board |
| 40 | + or row - col in diagonal_right_collisions |
| 41 | + or row + col in diagonal_left_collisions |
| 42 | + ): |
| 43 | + continue |
| 44 | + |
| 45 | + depth_first_search( |
| 46 | + possible_board + [col], |
| 47 | + diagonal_right_collisions + [row - col], |
| 48 | + diagonal_left_collisions + [row + col], |
| 49 | + boards, |
| 50 | + n, |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +def n_queens_solution(n: int) -> None: |
| 55 | + boards = [] |
| 56 | + depth_first_search([], [], [], boards, n) |
| 57 | + |
| 58 | + """ Print all the boards """ |
| 59 | + for board in boards: |
| 60 | + for column in board: |
| 61 | + print(column) |
| 62 | + print("") |
| 63 | + |
| 64 | + print(len(boards), "solutions were found.") |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + import doctest |
| 69 | + doctest.testmod() |
| 70 | + n_queens_solution(4) |
0 commit comments