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

相关推荐
Pniubi1 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊7 小时前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊9 小时前
LeetCode3421~3440题目解析
java·leetcode
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路1 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
Pniubi1 天前
力扣239.滑动窗口最大值(优先队列)
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3281~3300题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3261~3280题目解析
java·leetcode