leetcode-79. 单词搜索

题目

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

提示:

board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3

解题思路

dfs, change the value in matrix for keeping track of visited nodes

Time complexity: o ( m ∗ n ) o(m * n) o(mn) m , n m, n m,n分别是board的宽度和高度
Space complexity: o ( m ∗ n + l e n ( w o r d ) ) o(m * n + len(word)) o(mn+len(word))

代码

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        visited = set()
        def dfs(x: int, y: int, index: int) -> bool:
            if index == len(word) - 1:
                return True
            res = False
            for dz in (-1, 1):
                if 0 <= x + dz < m and board[x + dz][y] == word[index + 1] and (x + dz, y) not in visited:
                    visited.add((x + dz, y))
                    res |= dfs(x + dz, y, index + 1)
                    visited.remove((x + dz, y))
                if 0 <= y + dz < n and board[x][y + dz] == word[index + 1] and (x, y + dz) not in visited:
                    visited.add((x, y + dz))
                    res |= dfs(x, y + dz, index + 1)
                    visited.remove((x, y + dz))
            return res
        res = False
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    visited.add((i, j))
                    res |= dfs(i, j, 0)
                    visited.remove((i, j))
                    if res:
                        return True
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值