- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathword_search.py
162 lines (127 loc) · 4.32 KB
/
word_search.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""
Author : Alexander Pantyukhin
Date : November 24, 2022
Task:
Given an m x n grid of characters board and a string word,
return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example:
Matrix:
---------
|A|B|C|E|
|S|F|C|S|
|A|D|E|E|
---------
Word:
"ABCCED"
Result:
True
Implementation notes: Use backtracking approach.
At each point, check all neighbors to try to find the next letter of the word.
leetcode: https://leetcode.com/problems/word-search/
"""
defget_point_key(len_board: int, len_board_column: int, row: int, column: int) ->int:
"""
Returns the hash key of matrix indexes.
>>> get_point_key(10, 20, 1, 0)
200
"""
returnlen_board*len_board_column*row+column
defexits_word(
board: list[list[str]],
word: str,
row: int,
column: int,
word_index: int,
visited_points_set: set[int],
) ->bool:
"""
Return True if it's possible to search the word suffix
starting from the word_index.
>>> exits_word([["A"]], "B", 0, 0, 0, set())
False
"""
ifboard[row][column] !=word[word_index]:
returnFalse
ifword_index==len(word) -1:
returnTrue
traverts_directions= [(0, 1), (0, -1), (-1, 0), (1, 0)]
len_board=len(board)
len_board_column=len(board[0])
fordirectionintraverts_directions:
next_i=row+direction[0]
next_j=column+direction[1]
ifnot (0<=next_i<len_boardand0<=next_j<len_board_column):
continue
key=get_point_key(len_board, len_board_column, next_i, next_j)
ifkeyinvisited_points_set:
continue
visited_points_set.add(key)
ifexits_word(board, word, next_i, next_j, word_index+1, visited_points_set):
returnTrue
visited_points_set.remove(key)
returnFalse
defword_exists(board: list[list[str]], word: str) ->bool:
"""
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE")
True
>>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB")
False
>>> word_exists([["A"]], "A")
True
>>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB")
False
>>> word_exists([["A"]], 123)
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([["A"]], "")
Traceback (most recent call last):
...
ValueError: The word parameter should be a string of length greater than 0.
>>> word_exists([[]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
>>> word_exists([["A"], [21]], "AB")
Traceback (most recent call last):
...
ValueError: The board should be a non empty matrix of single chars strings.
"""
# Validate board
board_error_message= (
"The board should be a non empty matrix of single chars strings."
)
len_board=len(board)
ifnotisinstance(board, list) orlen(board) ==0:
raiseValueError(board_error_message)
forrowinboard:
ifnotisinstance(row, list) orlen(row) ==0:
raiseValueError(board_error_message)
foriteminrow:
ifnotisinstance(item, str) orlen(item) !=1:
raiseValueError(board_error_message)
# Validate word
ifnotisinstance(word, str) orlen(word) ==0:
raiseValueError(
"The word parameter should be a string of length greater than 0."
)
len_board_column=len(board[0])
foriinrange(len_board):
forjinrange(len_board_column):
ifexits_word(
board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)}
):
returnTrue
returnFalse
if__name__=="__main__":
importdoctest
doctest.testmod()