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

相关推荐
hanlin0311 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
程序猿乐锅17 小时前
【数据结构与算法 | 第七篇】二维数组:力扣48,54,59,151
算法·leetcode·职场和发展
青山木17 小时前
Hot 100 --- 组合总和
java·数据结构·算法·leetcode
zander25817 小时前
LeetCode 46. 全排列
算法·leetcode·深度优先
会编程的土豆20 小时前
LeetCode 热题 HOT100(一):哈希表与双指针入门(Go 实现)
算法·leetcode·职场和发展
Tisfy20 小时前
LeetCode 3518.最小回文排列 II:试填法(组合数学)
算法·leetcode·题解·组合数学·计数·回文串·试填法
小poop1 天前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
玖玥拾2 天前
LeetCode 27 移除元素
算法·leetcode
hanlin032 天前
刷题笔记:力扣第704、977、209题(数组相关)
笔记·算法·leetcode
Rabitebla2 天前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode