leetcode 79. Word Search (python)

Here Insert Picture Description
Solution:
This problem is a traversal search problem, we can be solved by backtracking algorithm.

  1. In this problem, we need for each cell in the two-dimensional grid and traversed to find a matching word;
    we first create a loop to traverse the floor of each cell;
    code as follows:
class Solution:
    def exist(self, board, word):

        #设置数组中的元素只能被使用一次
        used = [[False] * len(board[0]) for i in range(len(board))]
        # print(used)


        for i in range(len(board)):
            for j in range(len(board[0])):

                if(self.dfs_search(board, i, j,word,0,len(word) - 1)):
                    return True
        return False
  1. At the same time, moving within the grid, we can find direction and word letter in a match (in practice need to exclude came to this position in four directions, only three directions; but this we need to write code to exclude, and direction of each element to be excluded when looking different, so we still write code in four directions)
    code is as follows:
    def dfs_search(self, board, x, y, word,index,length_word):

        if board[x][y] != word[0]:
            return False

        #递归终止条件
        if index == length_word:
            return True

        #四个方向进行遍历
        # print(x,y)
        # print(word[0])
        # print('index,',index)
        # print('word',len(word) - 1)
        # if board[x][y] == word[0]:

            # used[x][y] = True
        tmp = board[x][y]
        board[x][y] = 0


        #向下遍历
        if (x < len(board) - 1 and self.dfs_search(board, x + 1, y, word[1:],index + 1,length_word)) or \
            (y < len(board[0]) - 1 and self.dfs_search(board, x, y + 1, word[1:],index + 1,length_word)) or \
            (x > 0 and self.dfs_search(board, x - 1, y, word[1:], index + 1,length_word)) or \
            (y > 0 and self.dfs_search(board, x, y - 1, word[1:], index + 1,length_word)):

                    return True
        


        board[x][y] = tmp


        return False
  1. In the above code we performed tmp = board [x] [y], board [x] [y] = operator 0, is to prevent repeated accesses, i.e. after entering dfs recursion, if repeat visits, the Board [ ! x] [y] = word [0], it will return immediately; us set an access operation reduces array size and the same board, to improve the spatial and temporal complexity;
  2. And if during the backtracking process, if four directions are not found, we need to backtrack, return a recursive, recursive before a return, we need to restore the state, we need to set the board [x] [y ] = tmp.
  3. Because this problem is to find a path to return true after the match; therefore, if any condition is true; we can immediately return true; return through layers of recursion, exist function returns true;
  4. As long as traversing the grid to find a path, the function returns true is true; and all the grid traversed are false, it returns false.

The complete code:

class Solution:
    def exist(self, board, word):

        #设置数组中的元素只能被使用一次
        used = [[False] * len(board[0]) for i in range(len(board))]
        # print(used)


        for i in range(len(board)):
            for j in range(len(board[0])):

                if(self.dfs_search(board, i, j,word,0,len(word) - 1)):
                    return True
        return False





    def dfs_search(self, board, x, y, word,index,length_word):

        if board[x][y] != word[0]:
            return False

        #递归终止条件
        if index == length_word:
            return True

        #四个方向进行遍历
        # print(x,y)
        # print(word[0])
        # print('index,',index)
        # print('word',len(word) - 1)
        # if board[x][y] == word[0]:

            # used[x][y] = True
        tmp = board[x][y]
        board[x][y] = 0


        #向下遍历
        if (x < len(board) - 1 and self.dfs_search(board, x + 1, y, word[1:],index + 1,length_word)) or \
            (y < len(board[0]) - 1 and self.dfs_search(board, x, y + 1, word[1:],index + 1,length_word)) or \
            (x > 0 and self.dfs_search(board, x - 1, y, word[1:], index + 1,length_word)) or \
            (y > 0 and self.dfs_search(board, x, y - 1, word[1:], index + 1,length_word)):

                    return True
        


        board[x][y] = tmp


        return False

Here Insert Picture Description
Also record what AC process this question:
Firstly, the method is relatively easy to think of setting up an array of the same size and board, to record whether each cell is accessed; time complexity is high, but easy to understand:

class Solution:
    def exist(self, board, word):

        #设置数组中的元素只能被使用一次
        used = [[False] * len(board[0]) for i in range(len(board))]
        # print(used)


        for i in range(len(board)):
            for j in range(len(board[0])):

                if(self.dfs_search(board, i, j,word,0,len(word) - 1,[[False] * len(board[0]) for i in range(len(board))])):
                    return True
        return False





    def dfs_search(self, board, x, y, word,index,length_word,used):

        #递归终止条件
        if index == length_word and board[x][y] == word[0]:
            return True

        #四个方向进行遍历
        # print(x,y)
        # print(word[0])
        # print('index,',index)
        # print('word',len(word) - 1)
        if board[x][y] == word[0]:

            used[x][y] = True


            #向下遍历
            if x < len(board) - 1:
                if used[x + 1][y] == False:

                    if(self.dfs_search(board, x + 1, y, word[1:],index + 1,length_word,used)):

                        return True
                    # else:
                    #     #回溯过程中设置未访问
                    #     used[x][y] = False


            #向右遍历
            if y < len(board[0]) - 1:
                # print("###")
                # print(x,y+1)
                if used[x][y + 1] == False:

                    if(self.dfs_search(board, x, y + 1, word[1:],index + 1,length_word,used)):

                        return True
                    # else:

                    #     used[x][y] = False
            #向上遍历
            if x > 0:
                if used[x - 1][y] == False:

                    if(self.dfs_search(board, x - 1, y, word[1:], index + 1,length_word,used)):
                        return True

                    # else:

                    #     used[x][y] = False
            #向左遍历
            if y > 0:
                if used[x][y - 1] == False:
                    if(self.dfs_search(board, x, y - 1, word[1:], index + 1,length_word,used)):
                        return True

                    # else:

                    #     used[x][y] = False
            
            used[x][y] = False

            return False


        else:

            return False

Here Insert Picture Description
After reading explanations, their method is optimized, used to remove the array;
code as follows:

class Solution:
    def exist(self, board, word):

        #设置数组中的元素只能被使用一次
        used = [[False] * len(board[0]) for i in range(len(board))]
        # print(used)


        for i in range(len(board)):
            for j in range(len(board[0])):

                if(self.dfs_search(board, i, j,word,0,len(word) - 1)):
                    return True
        return False





    def dfs_search(self, board, x, y, word,index,length_word):
        if board[x][y] != word[0]:
            return False

        #递归终止条件
        if index == length_word:
            return True

        #四个方向进行遍历
        # print(x,y)
        #print(word[0])
        #print('index,',index)
        #print('word',len(word) - 1)
        # if board[x][y] == word[0]:

            # used[x][y] = True
        tmp = board[x][y]
        board[x][y] = 0


        #向下遍历
        if x < len(board) - 1:
            # if used[x + 1][y] == False:

                if(self.dfs_search(board, x + 1, y, word[1:],index + 1,length_word)):

                    return True
                # else:
                #     #回溯过程中设置未访问
                #     used[x][y] = False


        #向右遍历
        if y < len(board[0]) - 1:
            # print("###")
            # print(x,y+1)
            # if used[x][y + 1] == False:

                if(self.dfs_search(board, x, y + 1, word[1:],index + 1,length_word)):

                    return True
                # else:

                #     used[x][y] = False
        #向上遍历
        if x > 0:
            # if used[x - 1][y] == False:

                if(self.dfs_search(board, x - 1, y, word[1:], index + 1,length_word)):
                    return True

                # else:

                #     used[x][y] = False
        #向左遍历
        if y > 0:
            # if used[x][y - 1] == False:
                if(self.dfs_search(board, x, y - 1, word[1:], index + 1,length_word)):
                    return True

                # else:

                #     used[x][y] = False

        board[x][y] = tmp


        return False

Here Insert Picture Description
If the four back into one, the first code is the beginning, the time required minimum.

Published 100 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/cy_believ/article/details/104544369
Recommended