79. Word Search

79. Word Search

python 复制代码
import numpy as np

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m,n=len(board),len(board[0])
        dic=defaultdict(set)
        for i in range(m):
            for j in range(n):
                dic[board[i][j]].add((i,j))

        def dfs(cord,indx):
            if indx==lngth:
                # if word_isr:results.append(word[::-1])
                # else:results.append(word)
                return True
 
            ch=word[indx]
            i,j=cord
            for cand in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
                if cand in dic[ch]:
                    dic[ch].remove(cand)
                    flag=dfs(cand,indx+1)
                    dic[ch].add(cand)
                    if flag:return True
            return False
        

        lngth=len(word)
        for cord in list(dic[word[0]]):
            dic[word[0]].remove(cord)
            flag=dfs(cord,1)
            dic[word[0]].add(cord)
            if flag:return True
        return False

how to store the location that previously visited

相关推荐
2301_8074492018 分钟前
字符串相乘——力扣
java·算法·leetcode
yadanuof1 小时前
leetcode hot100 图论
leetcode·深度优先·图论
xiao--xin2 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
记得早睡~4 小时前
leetcode654-最大二叉树
javascript·数据结构·算法·leetcode
圣保罗的大教堂4 小时前
leetcode 2070. 每一个查询的最大美丽值 中等
leetcode
田梓燊6 小时前
leetcode 95.不同的二叉搜索树 Ⅱ
数据结构·算法·leetcode
孑么8 小时前
力扣 编辑距离
java·数据结构·算法·leetcode·职场和发展·贪心算法·动态规划
Dream it possible!15 小时前
LeetCode 热题 100_字符串解码(71_394_中等_C++)(栈)
c++·算法·leetcode
开心比对错重要17 小时前
leetcode69.x 的平方根
数据结构·算法·leetcode
且听风吟ayan19 小时前
leetcode day26 重复的子字符串
算法·leetcode·c#