这篇文章是程序自动发表的,详情可以见这里
—
categories: leetcode
tags: [python,leetcode,os]
channel:16
这篇文章是程序自动生成并发表的,详情见这里
这是leetcode的第212题–Word Search II
题目
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"]
思路
直接搜索如果遇到前缀几乎相同的,会重复很多次,很慢,所以可以利用trie树
show me the code
class node:
def __init__(self,val = None):
self.val = val
self.isKey = False
self.children = {}
def __getitem__(self,i):
return self.children[i]
def __iter__(self):
return iter(self.children.values())
def __setitem__(self,i,x):
self.children[i] = x
def __bool__(self):
return self.children!={}
def __str__(self):
return 'val: ' str(self.val) '\nchildren: ' ' '.join(self.children.keys())
def __repr__(self):
return str(self)
def __delitem(self,i):
del self[i]
class Trie(object):
def __init__(self):
self.root=node('')
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
if not word:return
nd = self.root
for i in word:
for child in nd:
if i==child.val:
nd = nd[i]
break
else:
newNode= node(i)
nd[i] = newNode
nd = newNode
else:nd.isKey = True
def display(self):
print('preOrderTraverse data of the Trie')
self.preOrder(self.root,'')
def preOrder(self,root,s):
s=s root.val
if root.isKey:
print(s)
for i in root:
self.preOrder(i,s)
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
self.trie = Trie()
for i in words:
self.trie.insert(i)
#self.trie.display()
self.rst = {}
self.data=board
self.n = len(board[0])
self.m = len(board)
for nd in self.trie.root:
for i in range(self.m):
for j in range(self.n):
if nd.val ==board[i][j]:
self.f(nd,i,j,'')
return list(self.rst.values())
def f(self,nd,i,j,s):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
if (not (0<=i<self.m and 0<=j<self.n) ) :return
if nd.val!=self.data[i][j]:return
s=s nd.val
if nd.isKey:self.rst[s]=s
tmp = self.data[i][j]
self.data[i][j]=None
bl = False
offset=[(1,0),(-1,0),(0,1),(0,-1)]
for child in nd:
for g,h in offset:
self.f(child,i g,j h,s)
self.data[i][j]=tmp