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

相关推荐
Nazarick11 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴12 小时前
斐波那契数列题解
算法·leetcode
Tisfy14 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
Navigator_Z19 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Nazarick19 小时前
力扣LeetCode热题(3)
java·算法·leetcode·贪心算法
Rain的Java大神之路20 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
Shaoshing21 小时前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
吞下星星的少年·-·21 小时前
力扣 162. 寻找峰值(枚举,二分查找)
算法·leetcode·枚举·二分
Shaoshing2 天前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
圣保罗的大教堂2 天前
leetcode 3884. 双端字符匹配 简单
leetcode