|
79 | 79 | from __future__ import annotations
|
80 | 80 |
|
81 | 81 |
|
| 82 | +from typing import List |
| 83 | + |
82 | 84 | def depth_first_search(
|
83 |
| - possible_board: list[int], |
84 |
| - diagonal_right_collisions: list[int], |
85 |
| - diagonal_left_collisions: list[int], |
86 |
| - boards: list[list[str]], |
| 85 | + possible_board: List[int], |
| 86 | + diagonal_right_collisions: List[int], |
| 87 | + diagonal_left_collisions: List[int], |
| 88 | + boards: List[List[str]], |
87 | 89 | n: int,
|
88 | 90 | ) -> None:
|
89 | 91 | """
|
90 |
| - >>> boards = [] |
91 |
| - >>> depth_first_search([], [], [], boards, 4) |
92 |
| - >>> for board in boards: |
93 |
| - ... print(board) |
94 |
| - ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] |
95 |
| - ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . '] |
| 92 | + Recursively search for all possible solutions to the N-Queens problem. |
| 93 | +
|
| 94 | + Parameters: |
| 95 | + - possible_board: List representing the columns occupied by queens. |
| 96 | + - diagonal_right_collisions: List to track collisions in the right diagonal. |
| 97 | + - diagonal_left_collisions: List to track collisions in the left diagonal. |
| 98 | + - boards: List to store valid N-Queens board configurations. |
| 99 | + - n: Size of the chessboard (N x N). |
| 100 | +
|
| 101 | + Returns: |
| 102 | + None |
96 | 103 | """
|
97 | 104 |
|
98 | 105 | # Get next row in the current board (possible_board) to fill it with a queen
|
@@ -129,13 +136,19 @@ def depth_first_search(
|
129 | 136 | continue
|
130 | 137 |
|
131 | 138 | # If it is False we call dfs function again and we update the inputs
|
132 |
| - depth_first_search( |
133 |
| - [*possible_board, col], |
134 |
| - [*diagonal_right_collisions, row - col], |
135 |
| - [*diagonal_left_collisions, row + col], |
136 |
| - boards, |
137 |
| - n, |
138 |
| - ) |
| 139 | + # Add new values to the current lists |
| 140 | + possible_board.append(col) |
| 141 | + diagonal_right_collisions.append(row - col) |
| 142 | + diagonal_left_collisions.append(row + col) |
| 143 | + |
| 144 | + # Recursive call with updated lists |
| 145 | + depth_first_search(possible_board, diagonal_right_collisions, diagonal_left_collisions, boards, n) |
| 146 | + |
| 147 | + # Backtrack by removing the last added values after returning from recursion |
| 148 | + possible_board.pop() |
| 149 | + diagonal_right_collisions.pop() |
| 150 | + diagonal_left_collisions.pop() |
| 151 | + |
139 | 152 |
|
140 | 153 |
|
141 | 154 | def n_queens_solution(n: int) -> None:
|
|
0 commit comments