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

相关推荐
良木林4 小时前
滑动窗口 - LeetCode hot 100
javascript·算法·leetcode·双指针·滑动窗口
hold?fish:palm6 小时前
7 接雨水
开发语言·c++·leetcode
tkevinjd8 小时前
力扣148-排序链表
算法·leetcode·链表
wabs6661 天前
关于图论【力扣797.所有可能的路径的思考】
算法·leetcode·图论
Navigator_Z1 天前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
兰令水1 天前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试
tkevinjd1 天前
力扣72-编辑距离
算法·leetcode·职场和发展
什巳2 天前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
什巳2 天前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826522 天前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode