Walls and Gates

Problem

You are given a m x n 2D grid initialized with these three possible values.

-1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

For example, given the 2D grid:

INF  -1  0  INF
INF  INF INF  -1
INF  -1  INF  -1
0    -1  INF INF

After running your function, the 2D grid should be:

  3  -1   0   1
  2   2   1  -1
  1  -1   2  -1
  0  -1   3   4

Solution

Recursion (more intuitive)

class Solution {

    public void wallsAndGates(int[][] rooms) {
        if (rooms == null || rooms.length == 0) return;
        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[0].length; j++) {
                if (rooms[i][j] == 0) bfs(rooms, i, j, 0);
            }
        }
    }

    private void bfs(int[][] rooms, int i, int j, int val) {
        if (i < 0 || j < 0 || i == rooms.length || j == rooms[0].length || val > rooms[i][j]) return;
        rooms[i][j] = val;
        bfs(rooms, i, j + 1, val + 1);
        bfs(rooms, i, j - 1, val + 1);
        bfs(rooms, i + 1, j, val + 1);
        bfs(rooms, i - 1, j, val + 1);
    }
}

Iteration (different idea from Recursion solution)

class Solution {

    int[][] moves = new int[][] {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};

    public void wallsAndGates(int[][] rooms) {
        if (rooms == null || rooms.length == 0) return;
        int m = rooms.length, n = rooms[0].length;
        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (rooms[i][j] == 0) q.offer(new int[]{i, j});
            }
        }
        while (!q.isEmpty()) {
            int[] indices = q.poll();
            int i = indices[0], j = indices[1];
            for (int[] move : moves) {
                int newI = i + move[0], newJ = j + move[1];
                if (newI < 0 || newJ < 0 || newI == rooms.length || newJ == rooms[0].length || rooms[newI][newJ] != Integer.MAX_VALUE)
                    continue;
                rooms[newI][newJ] = rooms[i][j] + 1;
                q.offer(new int[] {newI, newJ});
            }
        }
    }
}

Analysis

Very typical solution to traversal matrix
In the recursive solution, we only need to continue the bfs() if current level > rooms[i][j]
And we increase level every time calling bfs() method

In the iterative solution, it's original bfs implementation
Since we add the i, j where rooms[i][j] == 0 in queue with order
We just need to update it's nearby rooms (meaning only one level)
Then we offer() the current indices into queue
Since it's a queue, it will update all possible rooms with min values

results matching ""

    No results matching ""