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

相关推荐
代码小将5 小时前
力扣992做题笔记
算法·leetcode
编程绿豆侠5 小时前
力扣HOT100之二叉树:199. 二叉树的右视图
算法·leetcode·职场和发展
飞川撸码6 小时前
【LeetCode 热题100】17:电话号码的字母组合(详细解析)(Go语言版)
算法·leetcode·golang·dfs
蒟蒻小袁6 小时前
力扣面试150题--从前序与中序遍历序列构造二叉树
算法·leetcode·面试
鸡鸭扣9 小时前
leetcode hot100:解题思路大全
数据结构·python·算法·leetcode·力扣
June`10 小时前
专题五:floodfill算法(太平洋大西洋水流问题)
c++·算法·leetcode·深度优先·剪枝
exe45212 小时前
力扣每日一题5-19
java·算法·leetcode
ganjiee000712 小时前
leetcode 每日一题 1931. 用三种不同颜色为网格涂色
windows·python·leetcode
freyazzr14 小时前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
freyazzr15 小时前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论