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

相关推荐
Pniubi29 分钟前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
Pniubi1 小时前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
文丑颜不良啊2 小时前
LeetCode1461~1480题目解析
java·leetcode
Pniubi12 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
旖旎夜光1 天前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊1 天前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊1 天前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent1 天前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi1 天前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展