力扣每日一题2021-09-16单词搜索II

该博客讨论了如何利用深度优先搜索(DFS)和回溯策略解决LeetCode的212题——单词搜索II。博主指出,仅使用DFS会导致超时,因此引入了字母计数来优化,通过统计棋盘上每个字母出现的次数,提前判断单词是否可能在棋盘上形成。在DFS过程中,博主还展示了如何检查当前路径并进行下一步搜索。最后,博客提供了Python实现的解决方案,并解释了代码的工作原理。
摘要由CSDN通过智能技术生成

212.单词搜索II

题目描述

单词搜索II


思路:DFS回溯

纯用dfs回溯会超时,采用统计单词字母哥舒加速,如某个单词需要3个’a’,棋盘上只有1个’a’,那必然不构成这个单词。
DFS回溯

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        m, n = len(board), len(board[0])
        cnts = Counter()
        for i in range(m):
            for j in range(n):
                cnts[board[i][j]] += 1
        ans = []
        def dfs(word, idx, p, explored):
            if idx == len(word):
                return True
            if p in explored or p[0] < 0 or p[0] == m or p[1] < 0 or p[1] == n:
                return False
            if board[p[0]][p[1]] == word[idx]:
                explored.add(p)
                idx += 1
                for dx, dy in (0, 1), (1, 0), (-1, 0), (0, -1):
                    if dfs(word, idx, (p[0] + dx, p[1] + dy), explored):
                        return True
                explored.remove(p)
            return False
        for word in words:
            cur = Counter(word)
            canExists = True
            for c in cur:
                if cnts[c] < cur[c]:
                    canExists = False
                    break
            if not canExists:
                continue
            find = False
            for i in range(m):
                for j in range(n):
                    if dfs(word, 0, (i, j), set()):
                        ans.append(word)
                        find = True
                        break
                if find:
                    break
        return ans
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值