python解题 leetcde212. 单词搜索 II

题目:
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

示例:

输入:
words = [“oath”,“pea”,“eat”,“rain”] and board =
[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]

输出: [“eat”,“oath”]

代码
class TrieNode:

def __init__(self):
    self.next = [None for i in range(26)]
    self.word = None

class Solution(object):

def __init__(self):
    self.result = None 
    self.m = None
    self.n = None
 
 def findWords(self, board, words):
    """
    :type board: List[List[str]]
    :type words: List[str]
    :rtype: List[str]
    """
    if len(board) == 0 or len(board[0])==0:
        return []
    root = TrieNode()
    self.result = []
            # build Trie![在这里插入图片描述](https://blog.csdn.net/u013949069/article/details/78056102)
          
           for word in words:
        curr = root
        for char in word:
            idx = ord(char)-97
            if curr.next[idx] == None:
                curr.next[idx] = TrieNode()
            curr = curr.next[idx]
        curr.word = word
    
    # search on the board
    self.m, self.n = len(board), len(board[0])
    for i in range(self.m):
        for j in range(self.n):
            self.dfs(board, i, j, root)
    return self.result

def dfs(self, board, i, j, curr_node):
    tmp =  board[i][j]
    if tmp == '#' or curr_node.next[ord(tmp) - 97] == None:
        return
    board[i][j] = '#'
    curr_node = curr_node.next[ord(tmp) - 97]
    if curr_node.word != None:
        self.result.append(curr_node.word)
        curr_node.word = None  # cannot return immedially as there may still exist longer word
    moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    for move in moves:
        if 0 <= i+move[0] < self.m and 0 <= j+move[1] < self.n:
            self.dfs(board, i+move[0], j+ move[1], curr_node)
    board[i][j] = tmp 

#测试
words = [“oath”,“pea”,“eat”,“rain”]
board =[
[‘o’,‘a’,‘a’,‘n’],
[‘e’,‘t’,‘a’,‘e’],
[‘i’,‘h’,‘k’,‘r’],
[‘i’,‘f’,‘l’,‘v’]
]
A=Solution()
A.findWords(board=board,words=words)
print(A.result)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值