1
1
# https://www.geeksforgeeks.org/solve-crossword-puzzle/
2
2
3
+
3
4
def is_valid (puzzle : list [list [str ]], word : str , row : int , col : int ) -> bool :
4
5
"""
5
6
Check if a word can be placed at the given position.
@@ -9,10 +10,11 @@ def is_valid(puzzle: list[list[str]], word: str, row: int, col: int) -> bool:
9
10
True
10
11
"""
11
12
for i in range (len (word )):
12
- if row + i >= len (puzzle ) or puzzle [row + i ][col ] != '' :
13
+ if row + i >= len (puzzle ) or puzzle [row + i ][col ] != "" :
13
14
return False
14
15
return True
15
16
17
+
16
18
def place_word (puzzle : list [list [str ]], word : str , row : int , col : int ) -> None :
17
19
"""
18
20
Place a word at the given position.
@@ -25,6 +27,7 @@ def place_word(puzzle: list[list[str]], word: str, row: int, col: int) -> None:
25
27
for i in range (len (word )):
26
28
puzzle [row + i ][col ] = word [i ]
27
29
30
+
28
31
def remove_word (puzzle : list [list [str ]], word : str , row : int , col : int ) -> None :
29
32
"""
30
33
Remove a word from the given position.
@@ -35,7 +38,8 @@ def remove_word(puzzle: list[list[str]], word: str, row: int, col: int) -> None:
35
38
[['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]
36
39
"""
37
40
for i in range (len (word )):
38
- puzzle [row + i ][col ] = ''
41
+ puzzle [row + i ][col ] = ""
42
+
39
43
40
44
def solve_crossword (puzzle : list [list [str ]], words : list [str ]) -> bool :
41
45
"""
@@ -48,7 +52,7 @@ def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
48
52
"""
49
53
for row in range (len (puzzle )):
50
54
for col in range (len (puzzle [0 ])):
51
- if puzzle [row ][col ] == '' :
55
+ if puzzle [row ][col ] == "" :
52
56
for word in words :
53
57
if is_valid (puzzle , word , row , col ):
54
58
place_word (puzzle , word , row , col )
@@ -60,13 +64,14 @@ def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:
60
64
return False
61
65
return True
62
66
67
+
63
68
# Replace with your actual puzzle and words
64
- PUZZLE = [['' for _ in range (3 )] for _ in range (3 )]
65
- WORDS = [' cat' , ' dog' , ' pig' ]
69
+ PUZZLE = [["" for _ in range (3 )] for _ in range (3 )]
70
+ WORDS = [" cat" , " dog" , " pig" ]
66
71
67
72
if solve_crossword (PUZZLE , WORDS ):
68
- print (' Solution found:' )
73
+ print (" Solution found:" )
69
74
else :
70
- print (' No solution found:' )
75
+ print (" No solution found:" )
71
76
for row in PUZZLE :
72
- print (' ' .join (row ))
77
+ print (" " .join (row ))
0 commit comments