44
55Task:
66Given an m x n grid of characters board and a string word,
7- return the first valid path of coordinates found that matches
7+ return the first valid path of coordinates found that matches
88the word in the grid. If the word does not exist, return None.
99
1010The word can be constructed from letters of sequentially adjacent cells,
2424
2525Result: [(0, 0), (0, 1), (0, 2), (1, 2)]
2626
27- Implementation notes:
27+ Implementation notes:
28281. Use a backtracking (DFS) approach to explore all possible paths.
29292. At each cell, recursively check neighbors, in this question it's (Up, Down, Left, Right).
30303. Maintain a 'visited' set for each coordinate
3131 to ensure cells are not reused within the same search branch.
32- 4. If a path matches the word, return the list of coordinates.
33- 5. If a branch fails, 'backtrack' by removing the current cell from
32+ 4. If a path matches the word, return the list of coordinates.
33+ 5. If a branch fails, 'backtrack' by removing the current cell from
3434 the visited set and the path list to allow for other potential matches.
3535
3636Similar leetcode question that returns a bool: https://leetcode.com/problems/word-search/
@@ -84,15 +84,15 @@ def get_word_path(
8484 key = get_point_key (len_board , len_board_column , next_i , next_j )
8585 if key in visited_points_set :
8686 continue
87-
87+
8888 visited_points_set .add (key )
8989 result = get_word_path (
9090 board , word , next_i , next_j , word_index + 1 , visited_points_set , new_path
9191 )
92-
92+
9393 if result is not None :
9494 return result
95-
95+
9696 # Backtrack: remove key to try other paths
9797 visited_points_set .remove (key )
9898
@@ -133,7 +133,7 @@ def word_search_path(board: list[list[str]], word: str) -> list[tuple[int, int]]
133133 # Validate board input
134134 if not isinstance (board , list ) or len (board ) == 0 :
135135 raise ValueError (board_error_message )
136-
136+
137137 for row in board :
138138 if not isinstance (row , list ) or len (row ) == 0 :
139139 raise ValueError (board_error_message )
@@ -164,4 +164,5 @@ def word_search_path(board: list[list[str]], word: str) -> list[tuple[int, int]]
164164
165165if __name__ == "__main__" :
166166 import doctest
167- doctest .testmod ()
167+
168+ doctest .testmod ()
0 commit comments