MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solve_crossword

Function solve_crossword

backtracking/crossword_puzzle_solver.py:82–119  ·  view source on GitHub ↗

Solve the crossword puzzle using backtracking. >>> puzzle = [ ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''], ... ['', '', '', ''] ... ] >>> words = ['word', 'four', 'more', 'last'] >>> solve_crossword(puzzle, words) True

(puzzle: list[list[str]], words: list[str])

Source from the content-addressed store, hash-verified

80
81
82def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
83 """
84 Solve the crossword puzzle using backtracking.
85
86 >>> puzzle = [
87 ... ['', '', '', ''],
88 ... ['', '', '', ''],
89 ... ['', '', '', ''],
90 ... ['', '', '', '']
91 ... ]
92
93 >>> words = ['word', 'four', 'more', 'last']
94 >>> solve_crossword(puzzle, words)
95 True
96 >>> puzzle = [
97 ... ['', '', '', ''],
98 ... ['', '', '', ''],
99 ... ['', '', '', ''],
100 ... ['', '', '', '']
101 ... ]
102 >>> words = ['word', 'four', 'more', 'paragraphs']
103 >>> solve_crossword(puzzle, words)
104 False
105 """
106 for row in range(len(puzzle)):
107 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
120
121
122if __name__ == "__main__":

Callers 1

Calls 5

place_wordFunction · 0.85
remove_wordFunction · 0.85
is_validFunction · 0.70
removeMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected