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

相关推荐
希望有朝一日能如愿以偿34 分钟前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato41 分钟前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417
数据分析螺丝钉2 小时前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
￴ㅤ￴￴ㅤ9527超级帅2 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
鱼跃鹰飞3 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试
源代码•宸6 小时前
Leetcode—76. 最小覆盖子串【困难】
c++·经验分享·算法·leetcode·滑动窗口
百里守约学编程6 小时前
70. 爬楼梯
算法·leetcode·go
Mephisto.java12 小时前
【力扣 | SQL题 | 每日四题】力扣1783,1757,1747,1623,1468,1661
算法·leetcode
大二转专业12 小时前
408算法题leetcode--第21天
考研·算法·leetcode
Tisfy20 小时前
LeetCode 0983.最低票价:记忆化搜索
算法·leetcode·题解·记忆化搜索·哈希表