Skip to content

Commit 040437a

Browse files
Update n_queens_math.py
The first change reduces the memory overhead associated with creating new lists at each recursive step by modifying the same list and backtracking after each recursive call. This can make a significant difference in memory usage for large boards. The second change uses List from typing for better type hinting. Also, it clarifies the function's purpose with a more descriptive docstring
1 parent 9a572de commit 040437a

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

backtracking/n_queens_math.py

+30-17
Original file line numberDiff line numberDiff line change
@@ -79,20 +79,27 @@
7979
from __future__ import annotations
8080

8181

82+
from typing import List
83+
8284
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]],
8789
n: int,
8890
) -> None:
8991
"""
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
96103
"""
97104

98105
# Get next row in the current board (possible_board) to fill it with a queen
@@ -129,13 +136,19 @@ def depth_first_search(
129136
continue
130137

131138
# 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+
139152

140153

141154
def n_queens_solution(n: int) -> None:

0 commit comments

Comments
 (0)