Leetcode 286 Walls and Gates

Leetcode 286 Walls and Gates

It’s smart to enqueue all the 0s at the same time, rather than empty the queue of one 0 and enqueue the next. So whenever an empty room is reached, it must be from the closest gate.

private static final int EMPTY = Integer.MAX_VALUE;
private static final int GATE = 0;
private static final List<int[]> DIRECTIONS = Arrays.asList(
        new int[] { 1,  0},
        new int[] {-1,  0},
        new int[] { 0,  1},
        new int[] { 0, -1}
);

public void wallsAndGates(int[][] rooms) {
    int m = rooms.length;
    if (m == 0) return;
    int n = rooms[0].length;
    Queue<int[]> q = new LinkedList<>();
    for (int row = 0; row < m; row++) {
        for (int col = 0; col < n; col++) {
            if (rooms[row][col] == GATE) {
                q.add(new int[] { row, col });
            }
        }
    }
    while (!q.isEmpty()) {
        int[] point = q.poll();
        int row = point[0];
        int col = point[1];
        for (int[] direction : DIRECTIONS) {
            int r = row + direction[0];
            int c = col + direction[1];
            if (r < 0 || c < 0 || r >= m || c >= n || rooms[r][c] != EMPTY) {
                continue;
            }
            rooms[r][c] = rooms[row][col] + 1;
            q.add(new int[] { r, c });
        }
    }
}

For example:
step 1:
INF, -1, 0, INF
INF, INF, INF, -1
INF, -1, INF, -1
0, -1, INF, INF
Queue : (0,2), (3,0)

step 2:
INF, -1, 0, 1
INF, INF, 1, -1
1, -1, INF, -1
0, -1, INF, INF
Queue : (0,3),(1,2), (2,0)

step 3:
INF, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, INF, INF
Queue : (1,0),(1,1),(2,2)

step 4:
3, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, 3, INF
Queue : (0, 0) , (3,2)

step 4:
3, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, 3, 4
Queue : (3,3)

step 5:
Queue is null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值