[leetcode] 490. The Maze @ python

本文介绍了一个基于深度优先搜索(DFS)解决迷宫问题的方法。通过递归地探索迷宫路径,判断球能否从起点到达终点。算法的时间复杂度为O(mn),空间复杂度为O(mn)。

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

原题

https://leetcode.com/problems/the-maze/

解法

DFS. 定义dfs函数, 返回球从(x, y)出发, 是否能停在目的地. 回溯的条件是如果(x,y) 等于目的地, 返回True.如果(x, y)是已经访问过的, 返回False. 我们将访问过的位置放入visited, 然后在上下左右四个方向检查, 让球一直滚, 检查停住的地方是否为目的地, 如果有一个是, 那么返回True, 如果遍历完了之后球不会停在目的地, 返回False.

Time: O(mn)
Space: O(m
n)

代码

class Solution(object):
    def hasPath(self, maze, start, destination):
        """
        :type maze: List[List[int]]
        :type start: List[int]
        :type destination: List[int]
        :rtype: bool
        """
        def dfs(x, y):
            # return if the ball can stop at destination if starting at (x, y)
            if [x,y] == destination:
                return True
            if (x, y) in visited:
                return False
            visited.add((x, y))
            for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
                new_x, new_y = x, y
                # the ball rolls until hitting a wall
                while 0 <= new_x+dx < row and 0 <= new_y+dy < col and maze[new_x+dx][new_y+dy] == 0:
                    new_x += dx
                    new_y += dy
                if dfs(new_x, new_y):
                    return True
            return False
        
        row, col = len(maze), len(maze[0])
        visited = set()
        return dfs(start[0], start[1])
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值