1926. Nearest Exit from Entrance in Maze刷题笔记

问题描述
使用洪水漫灌算法即可

import collections
class Solution:
    def nearestExit(self, maze, entrance):
        directions = [(-1,0),(1,0),(0,-1),(0,1)]
        m = len(maze)
        n = len(maze[0])
        to_check = collections.deque([entrance])
        maze[entrance[0]][entrance[1]]="+"
        temp_q = collections.deque()
        path = 0
        success = 0
        while to_check and not success:
            path+=1
            while to_check and not success:
                x,y = to_check.popleft()
                for dx,dy in directions:
                    nx = x+dx
                    ny = y+dy
                    if 0<=nx<m and 0<=ny<n and maze[nx][ny]==".":
                        if nx==0 or nx==m-1 or ny==0 or ny==n-1:
                            success=1
                            break
                        else:
                            maze[nx][ny]="+"
                            temp_q.append([nx,ny])
            to_check = temp_q
            temp_q = collections.deque()
        if success:
            return path
        else:
            return -1


maze = [["+",".","+","+","+","+","+"],["+",".","+",".",".",".","+"],["+",".","+",".","+",".","+"],["+",".",".",".","+",".","+"],["+","+","+","+","+","+","."]]
entrance = [0, 1]


print(Solution().nearestExit(maze,entrance))

运行结果:
在这里插入图片描述
参考这篇博客
学到了以下:

  1. dirs = [0, 1, 0, -1, 0],y是x的索引+1对应的值
  2. 第二层循环使用len,可以避免temp_q的使用

代码如下

        directions = [0,-1,0,1,0]
        m = len(maze)
        n = len(maze[0])
        to_check = collections.deque([entrance])
        maze[entrance[0]][entrance[1]]="+"
        path = 0
        while to_check:
            path+=1
            for _ in range(len(to_check)):
                x,y = to_check.popleft()
                for j in range(4):
                    nx = x+directions[j]
                    ny = y+directions[j+1]
                    if 0<=nx<m and 0<=ny<n and maze[nx][ny]==".":
                        if nx==0 or nx==m-1 or ny==0 or ny==n-1:
                            return path
                        else:
                            maze[nx][ny]="+"
                            to_check.append([nx,ny])
        return -1

运行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值