Given a two-dimensional grid and a word, to find out whether the word exists in the grid.
Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", returns true.
Given word = "SEE", returns true.
Given word = "ABCB", returns false.
1 class Solution: 2 # (x-1,y) 3 # (x,y-1) (x,y) (x,y+1) 4 # (x+1,y) 5 directions= [(0,-1),(-1,0),(0,1),(1,0)] 6 def exist(self, board: List[List[str]], word: str) -> bool: 7 m = len(board) 8 if m == 0: 9 return False 10 n = len(board[0]) 11 12 marked = [[False for _ in range(n)] for_ In Range (m)] 13 is # search for each grid from scratch 14 for I in Range (m): 15 for J in Range (n-): 16 IF Self. __Search_word (Board, Word, 0, I, J , Marked, m, n-): . 17 return True 18 is return False . 19 DEF __search_word (Self, Board, Word, index, start_x, start_y, Marked, m, n-): 20 is # to write a recursive termination condition 21 is IF index == len (Word) -1 : 22 is return Board [start_x] [start_y] ==Word [index] 23 # the middle of a match, to continue searching for 24- IF Board [start_x] [start_y] == Word [index]: 25 # to occupy this position, the search is unsuccessful, then, to be freed 26 Marked [start_x] [ start_y] = True 27 for direction in self.directions: 28 new_x + = start_x direction [0] 29 new_y start_y + direction = [. 1 ] 30 # # Note: If a search word is successful, return 31 is IF 0 <= new_x <m and 0 <= new_y <n- and Not Marked [new_x] [new_y]and self.__search_word(board,word,index+1,new_x,new_y,marked,m,n): 32 return True 33 marked[start_x][start_y] = False 34 return False