Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create crossword_puzzle_solver.py #11011

Merged
merged 27 commits into from
Oct 28, 2023
Merged
Changes from 8 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6f90a16
Create crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
e2d5a02
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
1feac57
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 26, 2023
4781e0b
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
2a78274
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 26, 2023
d950484
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
3ec196d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 26, 2023
82256da
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
f4cd628
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 26, 2023
3684f44
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 26, 2023
3bdeefe
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 26, 2023
0571200
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 27, 2023
88ee942
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 27, 2023
9448cc2
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 27, 2023
49f6e4d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 27, 2023
236b159
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 27, 2023
5142ce2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 27, 2023
e37a7c9
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 27, 2023
77863f6
Update backtracking/crossword_puzzle_solver.py
cclauss Oct 28, 2023
ecac1fd
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 28, 2023
76dd3fe
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 28, 2023
947e09c
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 28, 2023
f211c61
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 28, 2023
f0239ae
Update crossword_puzzle_solver.py
Khushi-Shukla Oct 28, 2023
ac0f723
Apply suggestions from code review
cclauss Oct 28, 2023
13794aa
Update crossword_puzzle_solver.py
cclauss Oct 28, 2023
e6bd599
Update crossword_puzzle_solver.py
cclauss Oct 28, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions backtracking/crossword_puzzle_solver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""
Solve a crossword puzzle by placing words from the provided list into the puzzle.

Args:
puzzle (List[List[str]]): The crossword puzzle grid.
words (List[str]): List of words to place in the puzzle.

Returns:
Optional[List[List[str]]]: The solved crossword puzzle, or None if no solution is found.
"""
from typing import List, Optional

def solve_crossword(puzzle: List[List[str]], words: List[str]) -> Optional[List[List[str]]]:

rows, cols = len(puzzle), len(puzzle[0])

def is_valid_placement(word: str, row: int, col: int, direction: str) -> bool:
"""
Check if placing a word in a specific direction at a given position is valid.

Args:
word (str): The word to be placed.
row (int): The starting row position.
col (int): The starting column position.
direction (str): Either "across" or "down".

Returns:
bool: True if the placement is valid, otherwise False.
"""
if direction == "across":
return col + len(word) <= cols and all(puzzle[row][col + i] in ("", word[i]) for i in range(len(word)))
else: # direction == "down"
return row + len(word) <= rows and all(puzzle[row + i][col] in ("", word[i]) for i in range(len(word)))

def place_word(word: str, row: int, col: int, direction: str) -> None:
"""
Place a word in the crossword puzzle at a specific position and direction.

Args:
word (str): The word to be placed.
row (int): The starting row position.
col (int): The starting column position.
direction (str): Either "across" or "down".

Returns:
None
"""
if direction == "across":
for i in range(len(word)):
puzzle[row][col + i] = word[i]
else: # direction == "down"
for i in range(len(word)):
puzzle[row + i][col] = word[i]

def remove_word(word: str, row: int, col: int, direction: str) -> None:
"""
Remove a word from the crossword puzzle at a specific position and direction.

Args:
word (str): The word to be removed.
row (int): The starting row position.
col (int): The starting column position.
direction (str): Either "across" or "down".

Returns:
None
"""
if direction == "across":
for i in range(len(word)):
puzzle[row][col + i] = ""
else: # direction == "down"
for i in range(len(word)):
puzzle[row + i][col] = ""

def backtrack(puzzle: List[List[str]], words: List[str]) -> bool:
"""
Recursively backtrack to solve the crossword puzzle.

Args:
puzzle (List[List[str]]): The crossword puzzle grid.
words (List[str]): List of words to place in the puzzle.

Returns:
bool: True if a solution is found, otherwise False.
"""
for row in range(rows):
for col in range(cols):
if puzzle[row][col] == "":
for word in words[:]:
for direction in ["across", "down"]:
if is_valid_placement(word, row, col, direction):
place_word(word, row, col, direction)
words.remove(word)
if not words:
return True
if backtrack(puzzle, words):
return True
words.append(word)
remove_word(word, row, col, direction)
return False
return True

# Create a copy of the puzzle to preserve the original
copied_puzzle = [row[:] for row in puzzle]
if backtrack(copied_puzzle, words):
return copied_puzzle
else:
return None

# Example usage:
puzzle = [
["#", "#", "c", "#", "#", "#", "#"],
["#", "#", "r", "a", "c", "k", "#"],
["#", "#", "o", "#", "#", "#", "#"],
["#", "#", "r", "#", "b", "#", "#"],
["#", "#", "a", "a", "t", "a", "x"],
["#", "#", "t", "#", "i", "n", "#"],
["#", "#", "e", "#", "n", "#", "#"],
]
words = ["car", "rack", "bat", "cat", "rat", "in", "tax", "eat"]
solution = solve_crossword(puzzle, words)

if solution:
for row in solution:
print(" ".join(row))
else:
print("No solution found.")