55Task:
66Given an m x n grid of characters board and a string word,
77return the first valid path of coordinates found that matches
8+ return the first valid path of coordinates found that matches
89the word in the grid. If the word does not exist, return None.
910
1011The word can be constructed from letters of sequentially adjacent cells,
2627
2728Implementation notes:
28291. Use a backtracking (DFS) approach to explore all possible paths.
29- 2. At each cell, recursively check neighbors, in this question it's (Up, Down, Left, Right).
30+ 2. At each cell, recursively check neighbors.
31+ case, check: Up, Down, Left, Right.
30323. Maintain a 'visited' set for each coordinate
3133 to ensure cells are not reused within the same search branch.
32344. If a path matches the word, return the list of coordinates.
@@ -65,7 +67,7 @@ def get_word_path(
6567 return None
6668
6769 # Track current progress
68- new_path = current_path + [ (row , column )]
70+ new_path = [ * current_path , (row , column )]
6971
7072 # Base case
7173 if word_index == len (word ) - 1 :
@@ -84,15 +86,12 @@ def get_word_path(
8486 key = get_point_key (len_board , len_board_column , next_i , next_j )
8587 if key in visited_points_set :
8688 continue
87-
8889 visited_points_set .add (key )
8990 result = get_word_path (
9091 board , word , next_i , next_j , word_index + 1 , visited_points_set , new_path
9192 )
92-
9393 if result is not None :
9494 return result
95-
9695 # Backtrack: remove key to try other paths
9796 visited_points_set .remove (key )
9897
@@ -133,7 +132,6 @@ def word_search_path(board: list[list[str]], word: str) -> list[tuple[int, int]]
133132 # Validate board input
134133 if not isinstance (board , list ) or len (board ) == 0 :
135134 raise ValueError (board_error_message )
136-
137135 for row in board :
138136 if not isinstance (row , list ) or len (row ) == 0 :
139137 raise ValueError (board_error_message )
@@ -152,7 +150,8 @@ def word_search_path(board: list[list[str]], word: str) -> list[tuple[int, int]]
152150 # Main entry point
153151 for r in range (rows ):
154152 for c in range (cols ):
155- # Optimization: only trigger recursion if first char in board matches with first char in word input
153+ # Optimization: only trigger recursion if first
154+ # char in board matches with first char in word.
156155 if board [r ][c ] == word [0 ]:
157156 key = get_point_key (rows , cols , r , c )
158157 path_result = get_word_path (board , word , r , c , 0 , {key }, [])
0 commit comments