forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrossword_puzzle_solver.py
98 lines (82 loc) · 2.69 KB
/
crossword_puzzle_solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# https://www.geeksforgeeks.org/solve-crossword-puzzle/
def is_valid(puzzle: list[list[str]], word: str, row: int, col: int) -> bool:
"""
Check if a word can be placed at the given position.
>>> puzzle = [
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', '']
... ]
>>> is_valid(puzzle, 'word', 0, 0)
True
"""
for i in range(len(word)):
if row + i >= len(puzzle) or puzzle[row + i][col] != "":
return False
return True
def place_word(puzzle: list[list[str]], word: str, row: int, col: int) -> None:
"""
Place a word at the given position.
>>> puzzle = [
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', '']
... ]
>>> place_word(puzzle, 'word', 0, 0)
>>> puzzle
[['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']]
"""
for i in range(len(word)):
puzzle[row + i][col] = word[i]
def remove_word(puzzle: list[list[str]], word: str, row: int, col: int) -> None:
"""
Remove a word from the given position.
>>> puzzle = [
... ['w', '', '', ''],
... ['o', '', '', ''],
... ['r', '', '', ''],
... ['d', '', '', '']
... ]
>>> remove_word(puzzle, 'word', 0, 0)
>>> puzzle
[['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
"""
for i in range(len(word)):
puzzle[row + i][col] = ""
def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
"""
Solve the crossword puzzle using backtracking.
>>> puzzle = [
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', ''],
... ['', '', '', '']
... ]
>>> words = ['word', 'four', 'more', 'last']
>>> solve_crossword(puzzle, words)
True
"""
for row in range(len(puzzle)):
for col in range(len(puzzle[0])):
if puzzle[row][col] == "":
for word in words:
if is_valid(puzzle, word, row, col):
place_word(puzzle, word, row, col)
words.remove(word)
if solve_crossword(puzzle, words):
return True
words.append(word)
remove_word(puzzle, word, row, col)
return False
return True
# Replace with your actual puzzle and words
PUZZLE = [["" for _ in range(3)] for _ in range(3)]
WORDS = ["cat", "dog", "pig"]
if solve_crossword(PUZZLE, WORDS):
print("Solution found:")
else:
print("No solution found:")
for row in PUZZLE:
print(" ".join(row))