LeetcodeMedium- [Interview Question 12. Path in Matrix]

Please design a function to judge whether there is a path containing all characters of a certain string in a matrix. The path can start from any grid in the matrix, and each step can move one grid to the left, right, up and down in the matrix. If a path passes through a grid of the matrix, the path cannot enter the grid again. For example, the following 3 × 4 matrix contains a path of the character string “bfce” (the letters in the path are marked in bold).

[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]

But the matrix does not contain the path of the string "abfb" because the first character b of the string occupies the second grid in the first row of the matrix, the path cannot enter this grid again.

 

Example 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true


Example 2:

输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false


prompt:

1 <= board.length <= 200
1 <= board [i] .length <= 200
Note: This question is the same as the main station 79 question: https://leetcode-cn.com/problems/word-search/

Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

Idea: Deep Search (dfs)

First traverse the array, try each point as a starting point, and then start searching from all directions of the starting point to see if a path can be found.

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if board == [] or board == [[]]:
            return False 
        # 标记该点是否在本次路径中搜索过
        self.visit = [[0]*len(board[0]) for _ in range(len(board))]
        # 每个点的周边点,分别为x,y的变化值
        self.dx = [0, 0, 0, 1, -1]
        self.dy = [0, 1, -1, 0, 0]
        self.board = board
        self.word = word
        for i in range(len(board)):
            for j in range(len(board[0])):
                rt = self.dfs(i, j, 0)
                if rt == True:
                    return True
        return False
    def dfs(self, x, y, cnt):
        if cnt == len(self.word):
            return True
        for i in range(len(self.dx)):
            xx = x + self.dx[i]
            yy = y + self.dy[i]
            if xx >= 0 and xx < len(self.board) and yy >= 0 and yy < len(self.board[0]) and self.visit[xx][yy] == 0:
                if self.board[xx][yy] == self.word[cnt]:
                    self.visit[xx][yy] = 1
                    # print(xx, yy)
                    rt = self.dfs(xx, yy, cnt+1)
                    if rt == True:
                        return True
                    self.visit[xx][yy] = 0
        return False

 

Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105385140