Simple Java code, 6ms


  • 0
    Y
    public class Solution {
        public void wallsAndGates(int[][] rooms) {
            
            int roomsLen = rooms.length;
            
            for(int row=0; row<roomsLen; ++row){
                int rowLen = rooms[row].length;
                for(int col=0; col<rowLen; ++col){
                    if (rooms[row][col] == 0){
                        startPath(rooms, row, col, 1);
                    }
                }
            }
        }
        
        public void startPath(int [][] rooms, int row, int col, int value){
            generatePath(rooms, row, col - 1, value);
            generatePath(rooms, row, col + 1, value);
            generatePath(rooms, row - 1, col, value);
            generatePath(rooms, row + 1, col, value);
        }
        
        public void generatePath(int [][] rooms, int row, int col, int value){
            if (col < 0 || row < 0 || row >= rooms.length || col >= rooms[row].length || rooms[row][col] <= value){
                return;
            }
            rooms[row][col] = value;
            startPath(rooms, row, col, value + 1);
        }
        
    }
    

Log in to reply
 

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