leetcode.array--79. Word Search

题目:79. Word Search

题目链接:https://leetcode.com/problems/word-search/description/

大致意思呢,是给定一个二维数组,每个元素均是一个字母,要求在数组中寻找给定的字符串,每个元素只能使用一次。如果能找到返回True,否则返回False。例如:

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

当目标字符串为"SEE"时,可以在数组中找到(右下角三个组成SEE),返回True。

可以用DFS来写,中间搜索过程中抛弃超过指定字符串长度的分支,找到一个结果返回即可。

Python:

class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        self.res = False
        def cango(x,y,rows,cols):
            return x>=0 and x<rows and y>=0 and y<cols
        rows=len(board)
        cols=len(board[0])
        direct=[(0,1),(1,0),(0,-1),(-1,0)]
        vis=set()
        def dfs(target,board,x,y,step,path):
            vis.add((x,y))
            if step==len(target) and path==target:
                self.res=True
                return
            if step>len(target):
                return
            for i in range(4):
                if self.res==True:
                    return
                nx,ny=x+direct[i][0],y+direct[i][1]
                if cango(nx,ny,rows,cols) and (nx,ny) not in vis and board[nx][ny]==target[step]:
                    dfs(target,board,nx,ny,step+1,path+board[nx][ny])
                    vis.remove((nx,ny))
        for i in range(rows):
            for j in range(cols):
                if board[i][j]==word[0]:
                    vis.clear()
                    self.res=False
                    dfs(word,board,i,j,1,''+word[0])
                    if self.res==True:
                        return True
        return False


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值