【Leetcode】1926. Nearest Exit from Entrance in Maze

题目地址:

https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/

给定一个 m × n m\times n m×n的网格,.代表空地,+代表障碍物,再给定起点,问从起点出发,每一步可以上下左右走一格,走到出口至少需要多少步。出口指的是在边界的非障碍物的位置。

直接BFS即可。代码如下:

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public int nearestExit(char[][] maze, int[] entrance) {
        Queue<int[]> q = new LinkedList<>();
        q.offer(entrance);
        boolean[][] vis = new boolean[maze.length][maze[0].length];
        vis[entrance[0]][entrance[1]] = true;
        int[] d = {-1, 0, 1, 0, -1};
        int res = 0;
        while (!q.isEmpty()) {
            res++;
            for (int i = q.size() - 1; i >= 0; i--) {
                int[] cur = q.poll();
                for (int j = 0; j < 4; j++) {
                    int nextX = cur[0] + d[j], nextY = cur[1] + d[j + 1];
                    if (0 <= nextX && nextX < maze.length && 0 <= nextY && nextY < maze[0].length && maze[nextX][nextY] != '+' && !vis[nextX][nextY]) {
                        if (check(nextX, nextY, maze)) {
                            return res;
                        }
                        
                        vis[nextX][nextY] = true;
                        q.offer(new int[]{nextX, nextY});
                    }
                }
            }
        }
        
        return -1;
    }
    
    private boolean check(int x, int y, char[][] maze) {
        return x == 0 || x == maze.length - 1 || y == 0 || y == maze[0].length - 1;
    }
}

时空复杂度 O ( m n ) O(mn) O(mn)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值