Skip to content

Commit 06b0756

Browse files
Ewanjohndennispre-commit-ci[bot]cclauss
authored
Improve crossword puzzle solver implementation (#14568)
* Improve crossword puzzle solver implementation The original `is_valid` returned `False` for any non-empty cell, which meant two words sharing a letter could never be placed together. Since crossword grids are built on exactly those intersections, this broke the core use case. Related to that, `remove_word` during backtracking blindly blanked every cell of the removed word, wiping out letters that belonged to already-placed crossing words. The fix snapshots the grid before placement and only clears cells that were empty beforehand. There was also a mutation bug: `words.remove(word)` does an O(n) scan and modifies state shared across the call stack, replaced here with a local slice per frame. On top of the fixes, the solver now tries the longest word first at each level, a standard "most-constrained variable" heuristic that cuts down backtracks significantly on larger inputs. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Refactor character check in crossword solver --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 2a3a697 commit 06b0756

1 file changed

Lines changed: 66 additions & 75 deletions

File tree

‎backtracking/crossword_puzzle_solver.py‎

Lines changed: 66 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,28 @@ def is_valid(
66
) -> bool:
77
"""
88
Check if a word can be placed at the given position.
9+
A cell is valid if it is empty or already contains the correct letter
10+
(enabling crossing/intersection between words).
911
10-
>>> puzzle = [
11-
... ['', '', '', ''],
12-
... ['', '', '', ''],
13-
... ['', '', '', ''],
14-
... ['', '', '', '']
15-
... ]
12+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
13+
... ['', '', '', ''], ['', '', '', '']]
1614
>>> is_valid(puzzle, 'word', 0, 0, True)
1715
True
18-
>>> puzzle = [
19-
... ['', '', '', ''],
20-
... ['', '', '', ''],
21-
... ['', '', '', ''],
22-
... ['', '', '', '']
23-
... ]
2416
>>> is_valid(puzzle, 'word', 0, 0, False)
2517
True
18+
>>> puzzle2 = [['w', '', ''], ['o', '', ''], ['r', '', ''], ['d', '', '']]
19+
>>> is_valid(puzzle2, 'word', 0, 0, True)
20+
True
21+
>>> is_valid(puzzle2, 'cat', 0, 0, True)
22+
False
2623
"""
27-
for i in range(len(word)):
28-
if vertical:
29-
if row + i >= len(puzzle) or puzzle[row + i][col] != "":
30-
return False
31-
elif col + i >= len(puzzle[0]) or puzzle[row][col + i] != "":
24+
rows, cols = len(puzzle), len(puzzle[0])
25+
for i, ch in enumerate(word):
26+
r, c = (row + i, col) if vertical else (row, col + i)
27+
if r >= rows or c >= cols:
28+
return False
29+
cell = puzzle[r][c]
30+
if cell not in ("", ch):
3231
return False
3332
return True
3433

@@ -37,95 +36,87 @@ def place_word(
3736
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
3837
) -> None:
3938
"""
40-
Place a word at the given position.
41-
42-
>>> puzzle = [
43-
... ['', '', '', ''],
44-
... ['', '', '', ''],
45-
... ['', '', '', ''],
46-
... ['', '', '', '']
47-
... ]
39+
Place a word at the given position in the puzzle.
40+
41+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
42+
... ['', '', '', ''], ['', '', '', '']]
4843
>>> place_word(puzzle, 'word', 0, 0, True)
4944
>>> puzzle
5045
[['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']]
5146
"""
52-
for i, char in enumerate(word):
47+
for i, ch in enumerate(word):
5348
if vertical:
54-
puzzle[row + i][col] = char
49+
puzzle[row + i][col] = ch
5550
else:
56-
puzzle[row][col + i] = char
51+
puzzle[row][col + i] = ch
5752

5853

5954
def remove_word(
60-
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
55+
puzzle: list[list[str]],
56+
word: str,
57+
row: int,
58+
col: int,
59+
vertical: bool,
60+
snapshot: list[list[str]],
6161
) -> None:
6262
"""
63-
Remove a word from the given position.
64-
65-
>>> puzzle = [
66-
... ['w', '', '', ''],
67-
... ['o', '', '', ''],
68-
... ['r', '', '', ''],
69-
... ['d', '', '', '']
70-
... ]
71-
>>> remove_word(puzzle, 'word', 0, 0, True)
63+
Remove a word from the puzzle, restoring only cells that were empty
64+
before placement. Cells shared with crossing words are preserved.
65+
66+
>>> puzzle = [['w', 'o', 'r', 'd'], ['', '', '', ''],
67+
... ['', '', '', ''], ['', '', '', '']]
68+
>>> snap = [['', 'o', 'r', 'd'], ['', '', '', ''],
69+
... ['', '', '', ''], ['', '', '', '']]
70+
>>> remove_word(puzzle, 'word', 0, 0, False, snap)
7271
>>> puzzle
73-
[['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
72+
[['', 'o', 'r', 'd'], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
7473
"""
7574
for i in range(len(word)):
76-
if vertical:
77-
puzzle[row + i][col] = ""
78-
else:
79-
puzzle[row][col + i] = ""
75+
r, c = (row + i, col) if vertical else (row, col + i)
76+
if snapshot[r][c] == "":
77+
puzzle[r][c] = ""
8078

8179

8280
def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
8381
"""
8482
Solve the crossword puzzle using backtracking.
83+
Words are tried longest-first to prune the search space early.
84+
Intersections between words (shared letters) are supported.
8585
86-
>>> puzzle = [
87-
... ['', '', '', ''],
88-
... ['', '', '', ''],
89-
... ['', '', '', ''],
90-
... ['', '', '', '']
91-
... ]
92-
93-
>>> words = ['word', 'four', 'more', 'last']
94-
>>> solve_crossword(puzzle, words)
86+
>>> puzzle = [['', '', '', ''], ['', '', '', ''],
87+
... ['', '', '', ''], ['', '', '', '']]
88+
>>> solve_crossword(puzzle, ['word', 'four', 'more', 'last'])
9589
True
96-
>>> puzzle = [
97-
... ['', '', '', ''],
98-
... ['', '', '', ''],
99-
... ['', '', '', ''],
100-
... ['', '', '', '']
101-
... ]
102-
>>> words = ['word', 'four', 'more', 'paragraphs']
103-
>>> solve_crossword(puzzle, words)
90+
>>> puzzle2 = [['', '', '', ''], ['', '', '', ''],
91+
... ['', '', '', ''], ['', '', '', '']]
92+
>>> solve_crossword(puzzle2, ['word', 'four', 'more', 'paragraphs'])
10493
False
10594
"""
95+
if not words:
96+
return True
97+
98+
remaining = sorted(words, key=len, reverse=True)
99+
word, rest = remaining[0], remaining[1:]
100+
106101
for row in range(len(puzzle)):
107102
for col in range(len(puzzle[0])):
108-
if puzzle[row][col] == "":
109-
for word in words:
110-
for vertical in [True, False]:
111-
if is_valid(puzzle, word, row, col, vertical):
112-
place_word(puzzle, word, row, col, vertical)
113-
words.remove(word)
114-
if solve_crossword(puzzle, words):
115-
return True
116-
words.append(word)
117-
remove_word(puzzle, word, row, col, vertical)
118-
return False
119-
return True
103+
for vertical in (True, False):
104+
if is_valid(puzzle, word, row, col, vertical):
105+
snapshot = [r[:] for r in puzzle]
106+
place_word(puzzle, word, row, col, vertical)
107+
if solve_crossword(puzzle, rest):
108+
return True
109+
remove_word(puzzle, word, row, col, vertical, snapshot)
110+
111+
return False
120112

121113

122114
if __name__ == "__main__":
123115
PUZZLE = [[""] * 3 for _ in range(3)]
124116
WORDS = ["cat", "dog", "car"]
125-
126117
if solve_crossword(PUZZLE, WORDS):
127118
print("Solution found:")
128119
for row in PUZZLE:
129-
print(" ".join(row))
120+
print(" ".join(cell or "." for cell in row))
130121
else:
131-
print("No solution found:")
122+
print("No solution found.")

0 commit comments

Comments
 (0)