美文网首页
leetcode79. Word Search

leetcode79. Word Search

作者: 就是果味熊 | 来源:发表于2020-06-22 11:03 被阅读0次

原文地址https://leetcode.com/problems/binary-tree-paths/

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']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
    
        for i in range(m):
            for j in range(n):
                if self.dfs(board,i,j,word):
                    return True
        return False
        
        
    def dfs(self,board,i,j,word):
        if len(word) == 0:
            return True
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0]!=board[i][j]:
            return False
        tmp = board[i][j]
        board[i][j] = "#"
        res = self.dfs(board,i-1,j,word[1:]) or self.dfs(board,i+1,j,word[1:]) or self.dfs(board,i,j-1,word[1:]) or self.dfs(board,i,j+1,word[1:])
        board[i][j] = tmp
        return res

相关文章

网友评论

      本文标题:leetcode79. Word Search

      本文链接:https://www.haomeiwen.com/subject/dihxfktx.html