Leetcode 79 Word Search Python realization

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

Board = 
[
[ 'A', 'B', 'C', 'E'],
[ 'S', 'F.', 'C', 'S'],
[ 'A', 'D', 'E ',' E ']
] the Given Word = "ABCCED", return to true. the Given Word = "the SEE", return to true. the Given Word = "ABCB", return to false.





Review several ideas borrowed from others in which the code portion
class Solution:
     DEF exist (Self, Board: List [List [STR]], Word: STR) -> BOOL: 
        MAX_ROW = len (Board) -1 
        max_col = len (Board [0]) -. 1
         DEF BackTrack (Row, COL, S):
             IF len (S) == 0:
                 return True 
            LOCS = [[-Row. 1, COL], [+ Row. 1, COL], [Row,-COL. 1], [Row, + COL. 1 ] ]
             # Analyzing points up and down available, as long as there can be a return True if the dfs can return True 
            for LOC in LOCS:
                 IF LOC [0] <0 or LOC [0]> MAX_ROW or LOC [. 1] <0 orLOC [. 1]> max_col or Board [LOC [0]] [LOC [. 1]] =! S [0]:
                     Continue 
                # Reference other code, the current position into a non-alphabetic characters, represents been used 
                tmp = board [ LOC [0]] [LOC [. 1 ]] 
                Board [LOC [0]] [LOC [ . 1]] = " $ " 
                IF BackTrack (LOC [0], LOC [. 1], S [. 1 :]):
                     return True 
                Board [LOC [0]] [LOC [ . 1]] = tmp
             return False 
        
        for R & lt in Range (len (Board)):
             for C in Range (len (Board [0])):
                 IF board[r][c] == word[0]:
                    tmp = board[r][c]
                    board[r][c] = "$"
                    if backtrack(r,c,word[1:]):
                        return True
                    board[r][c] = tmp
        return False
        

 

Guess you like

Origin www.cnblogs.com/watch-fly/p/leetcode_79_watchfly.html