【Lintcode】663. Walls and Gates

题目地址:

https://www.lintcode.com/problem/walls-and-gates/description

给定一个二维矩阵,里面的 0 0 0代表门, − 1 -1 1代表障碍物, I N F INF INF代表空房间,要求修改原矩阵,使得每个位置代表该位置走到离它最近的门所需步数(每一步只能走四个方向并且不能走到障碍物上)。障碍物所在位置不需要修改,如果某个位置走不到门上,则维持其等于 I N F INF INF

思路是BFS。先将所有等于 0 0 0的位置入队,然后向外扩张,逐次更新每个点到 0 0 0的最短距离。代码如下:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    /**
     * @param rooms: m x n 2D grid
     * @return: nothing
     */
    public void wallsAndGates(int[][] rooms) {
        // write your code here
        if (rooms == null || rooms.length == 0 || rooms[0].length == 0) {
            return;
        }
        
        Queue<int[]> queue = new LinkedList<>();
        // 先将所有等于0的位置入队
        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[0].length; j++) {
                if (rooms[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            int x = cur[0], y = cur[1];
            // 取出相邻的非-1非0的点
            for (int[] next : getNexts(x, y, rooms)) {
                int nextX = next[0], nextY = next[1];
                // 如果从当前位置到这个位置距离更短,则更新之,并将其入队以便更新别的点
                if (rooms[nextX][nextY] > rooms[x][y] + 1) {
                    rooms[nextX][nextY] = rooms[x][y] + 1;
                    queue.offer(new int[]{nextX, nextY});
                }
            }
        }
    }
    
    private List<int[]> getNexts(int x, int y, int[][] rooms) {
        List<int[]> nexts = new ArrayList<>();
        int[] d = {0, 1, 0, -1, 0};
        for (int i = 0; i < 4; i++) {
            int nextX = x + d[i], nextY = y + d[i + 1];
            if (inBound(nextX, nextY, rooms) && rooms[nextX][nextY] != 0 && rooms[nextX][nextY] != -1) {
                nexts.add(new int[]{nextX, nextY});
            }
        }
        
        return nexts;
    }
    
    private boolean inBound(int x, int y, int[][] rooms) {
        return 0 <= x && x < rooms.length && 0 <= y && y < rooms[0].length;
    }
}

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值