212. Word Search II

212. Word Search II

python 复制代码
class Solution:
    
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        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))
        
        results=deque()

        word,lngth,word_isr='',0, False

        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

        ref=set()
        for i in range(m):
            for j in range(n-1):
                ref.add(board[i][j]+board[i][j+1])
        
        for j in range(n):
            for i in range(m-1):
                ref.add(board[i][j]+board[i+1][j])
        
        def check(word):
            for i in range(len(word)-1):
                if word[i]+word[i+1] not in ref:
                    if word[i+1]+word[i] not in ref:
                        return False
            return True

        for w in words:
            if check(w):
                if w[:6]==w[0]*6 or len(dic[w[-1]])<len(dic[w[0]]):
                    word=w[::-1]
                    word_isr=True
                else:
                    word=w
                    word_isr=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:break

        return results
        
  1. remove some string patterns that could never exist

  2. dic - letter with cords

相关推荐
超级大福宝12 小时前
【力扣48. 旋转图像】超好记忆版 + 口诀
c++·算法·leetcode
人道领域13 小时前
【LeetCode刷题日记】掌握二叉树遍历:栈实现的三种绝妙方法
算法·leetcode·职场和发展
阿Y加油吧13 小时前
二刷 LeetCode:动态规划经典双题复盘
算法·leetcode·动态规划
莫等闲-14 小时前
代码随想录一刷记录Day44——leetcode1143.最长公共子序列 53. 最大子序和
数据结构·c++·算法·leetcode·动态规划
承渊政道14 小时前
【动态规划算法】(背包问题经典模型与解题套路)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
m0_6294947316 小时前
LeetCode 热题 100-----18.矩阵置零
数据结构·leetcode·矩阵
阿Y加油吧16 小时前
二刷 LeetCode:两道经典贪心题复盘
算法·leetcode·职场和发展
Java成神之路-16 小时前
【LeetCode 刷题笔记】35. 搜索插入位置 | 二分查找经典入门题
算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
We་ct1 天前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划