Leetcode79. 单词搜索 Python实现

周报文学家
• 阅读 2187
  • 题目要求:

Leetcode79. 单词搜索 Python实现

  • 思路:

    • 先遍历数组,找到可能的起点
    • 定义一个helper函数,用来遍历当前起点的上下左右元素,看是否有符合给定单词的下一位的,如果又再递归调用helper函数
    • 当上下左右的下标越界或当前数组元素与当前的单词的字母不同时,返回False
  • 核心代码:
#遍历二维数组
for i in range(len(board)):
            for j in range(len(board[0])):
                   #调用helper函数
                if self.helper(board,i,j,word,0):
                    return True
        return False
#定义helper函数:
def helper(self,board,i,j,word,index):
        #如果当前的下标与单词的长度相等,说明前面的所有字母都找到了匹配,返回True
        if index == len(word):
            return True
        #如果当前的下标越界,或是当前的元素字母与单词中的字母不同,返回False
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[index]:
            return False
        #要把当前已经经过的数组元素标记
        board[i][j] = "*"
        #递归调用当前元素的上下左右,看有没有与单词的下一个字母相同的
        found = self.helper(board,i+1,j,word,index+1)\
                or self.helper(board,i,j+1,word,index+1)\
                or self.helper(board,i-1,j,word,index+1)\
                or self.helper(board,i,j-1,word,index+1)
        #已经标记的值要复原   
        board[i][j] = word[index]
        return found
  • 完整代码:
class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        for i in range(len(board)):
            for j in range(len(board[0])):
                if self.helper(board,i,j,word,0):
                    return True
        return False

    
    def helper(self,board,i,j,word,index):

        if index == len(word):
            return True

        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[index]:
            return False
        
        board[i][j] = "*"
        found = self.helper(board,i+1,j,word,index+1)\
                or self.helper(board,i,j+1,word,index+1)\
                or self.helper(board,i-1,j,word,index+1)\
                or self.helper(board,i,j-1,word,index+1)
        board[i][j] = word[index]
        return found
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
11个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
梦
4年前
微信小程序new Date()转换时间异常问题
微信小程序苹果手机页面上显示时间异常,安卓机正常问题image(https://imghelloworld.osscnbeijing.aliyuncs.com/imgs/b691e1230e2f15efbd81fe11ef734d4f.png)错误代码vardate'2021030617:00:00'vardateT
Stella981 Stella981
3年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
美凌格栋栋酱 美凌格栋栋酱
4个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
周报文学家
周报文学家
Lv1
折得一枝香在手,人间应未有。
文章
3
粉丝
0
获赞
0