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

相关推荐
Swift社区3 分钟前
LeetCode 396 - 旋转函数 (Rotate Function)
算法·leetcode·职场和发展
海琴烟Sunshine5 分钟前
leetcode 88.合并两个有序数组
python·算法·leetcode
new coder4 小时前
[算法练习]Day 7: 变长滑动窗口
数据结构·算法·leetcode
Tiny番茄10 小时前
leetcode 3. 无重复字符的最长子串
数据结构·python·算法·leetcode
Miraitowa_cheems16 小时前
LeetCode算法日记 - Day 68: 猜数字大小II、矩阵中的最长递增路径
数据结构·算法·leetcode·职场和发展·贪心算法·矩阵·深度优先
qq_5746562519 小时前
java-代码随想录第66天|Floyd 算法、A * 算法精讲 (A star算法)
java·算法·leetcode·图论
代码对我眨眼睛1 天前
739. 每日温度 LeetCode 热题 HOT 100
算法·leetcode
zycoder.1 天前
力扣面试经典150题day3第五题(lc69),第六题(lc189)
算法·leetcode·面试
_dindong1 天前
基础算法:滑动窗口
数据结构·学习·算法·leetcode·力扣
nju_spy2 天前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆