212. Word Search II--python

解题思路:
将待查找的单词存放在Trie(字典树)中,利用DFS(深度优先搜索)在board中搜索即可,每次查找成功,进行剪枝操作。

程序代码:

class TrieNode(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.childs = {}
        self.isWord = False


class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        useroot = self.root
        for i in range(len(word)):
            if word[i] in useroot.childs:
                useroot = useroot.childs[word[i]]
            else:
                useroot.childs[word[i]] = TrieNode()
                useroot = useroot.childs[word[i]]

        useroot.isWord = True

    def delete(self, word):
        useroot = self.root
        stack = []
        for i in range(len(word)):
            stack.append([useroot, word[i]])
            useroot = useroot.childs[word[i]]
            if useroot is None:
                return False
        if not useroot.isWord:
            return False
        elif useroot.childs:
            useroot.isWord = False
            return True
        else:
            while stack:
                node, string = stack.pop()
                del node.childs[string]
                if len(node.childs) or node.isWord:
                    break

            return True


class Solution(object):
    def findWords(self, board, words):
        """
        :type board: List[List[str]]
        :type words: List[str]
        :rtype: List[str]
        """
        ans = []
        tree = Trie()
        visited = [[False] * len(board[0]) for _ in range(len(board))]
        for i in range(len(words)):
            tree.insert(words[i])

        def dfs(x, y, root, word):
            root = root.childs.get(board[x][y])
            if not root:
                return
            visited[x][y] = True
            for dx, dy in zip((1, 0, -1, 0), (0, 1, 0, -1)):
                nx = x + dx
                ny = y + dy
                if nx < 0 or ny < 0 or nx > len(board) - 1 or ny > len(board[0]) - 1 or visited[nx][ny]:
                    continue
                dfs(nx, ny, root, word + board[nx][ny])
            if root.isWord:
                ans.append(word)
                tree.delete(word)
            visited[x][y] = False

        for i in range(len(board)):
            for j in range(len(board[0])):
                dfs(i, j, tree.root, board[i][j])
        return ans

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值