[一起来刷leetcode吧][3]--No.212 Word Search II.md

本文解析了LeetCode上第212题Word Search II的问题,介绍了如何使用Trie树来优化搜索过程,避免重复搜索相似前缀的情况,并提供了完整的Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文章是程序自动发表的,详情可以见这里

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值