Jianzhi offer brushing notes -12 path in the matrix

Insert picture description here
The idea that can be thought of in this question is to traverse the matrix, start with each node and use the backtracking method to separate the above, bottom, left, and right starting nodes to determine whether word[1:] exists. The letters of the nodes that have been visited are replaced with special symbols.
But in the specific implementation, I couldn't think clearly, mainly because the thinking of using multi-pointer movement was not established, and more practice was needed. Summarize the way to clarify the idea: the backtracking method needs to consider the following points: 1. End condition: When the pointer indicating the position of the matrix node is out of bounds, return false. When the symbol of the current matrix node is different from the current letter in word, return false. When the current node has been visited, return false. When none of the previous conditions return false, and the last letter in word has been accessed currently, return true.
2. Need to pass in the variable of the function: instead of passing in the entire board matrix, just pass in the index i, j representing the current position. And the index k that represents the letter currently searched in word. I was too constrained to the input of the main function given in the title, but in fact, I can define my own function in the main function given as a function to be called in a loop. .
3. Recursive work: It is mainly the change of the variable passed into the sub-problem. In this question, you need to call a function to access the four nodes, up, down, left, and right. Each node is represented by the change of pointers i and j. One thing that is easy to overlook is that the replaced node that has been visited needs to be restored at the end of the visit, and only the ancestor node seen by the child node has been replaced.

class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        def check(i,j,k):
            if not 0<=i<len(board) or not 0<=j<len(board[0]) or board[i][j] != word[k]: #可以用not来避免写两端分开的区间 
                return False
            elif k == len(word)-1:  #如果访问到最后一个字母并且匹配,匹配的判断在上面的if中
                return True

            tmp, board[i][j] = board[i][j], '#' #替换已访问节点
            res = check(i,j+1,k+1) or check(i+1,j,k+1) or check(i-1,j,k+1) or check(i,j-1,k+1)
            board[i][j] = tmp  #restore visited node
            return res

        for i in range(len(board)):
            for j in range(len(board[0])):
                if check(i,j,0): return True # 有一个匹配找到就返回true

        return False    #全部节点都未匹配,false

Guess you like

Origin blog.csdn.net/baidu_37360677/article/details/108571866