本文介绍: 【代码】212. Word Search II。
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
原文地址:https://blog.csdn.net/ujn20161222/article/details/135284577
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_51606.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。