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

相关推荐
happymaker06266 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
普通网友7 小时前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_7 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
罗超驿13 小时前
2.LeetCode 1089. 复写零——双指针解法学习笔记
java·算法·leetcode
khalil102013 小时前
代码随想录算法训练营Day-41动态规划08 | 121. 买卖股票的最佳时机、122.买卖股票的最佳时机II、123.买卖股票的最佳时机III
数据结构·c++·算法·leetcode·动态规划
1104.北光c°13 小时前
Leetcode215 三种写法完成数组中的第K个最大元素 【hot100算法个人笔记】【java写法】
java·笔记·程序人生·算法·leetcode·排序算法·快速选择
浅念-14 小时前
LeetCode最短路必看:BFS算法原理+经典题解
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
代码地平线15 小时前
【数据结构】二叉树详解:全代码逐行解析+6道LeetCode高频OJ题图解
数据结构·算法·leetcode
田梓燊15 小时前
翻转二叉树
leetcode
流年如夢15 小时前
顺序表(LeetCode)
c语言·数据结构·leetcode·职场和发展