JAVA DFS SOLUTION


  • 1
    Y
    public class Solution {
        public void wallsAndGates(int[][] rooms) {
            if(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)
                        fill(rooms, i, j, 0);
                }
            }
        }
        
        public void fill(int[][] rooms, int x, int y, int dis) {
            if(x < 0 || y < 0 || x >= rooms.length || y >= rooms[0].length  || rooms[x][y] == -1)
                return;
            if(rooms[x][y] == 0 && dis != 0 || rooms[x][y] != 0 && rooms[x][y] <= dis)
                return;
            rooms[x][y] = dis;
            fill(rooms, x + 1, y, dis + 1);
            fill(rooms, x, y + 1, dis + 1);
            fill(rooms, x - 1, y, dis + 1);
            fill(rooms, x, y - 1, dis + 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.