C#: Intuitive and Easy to Understand Solution. (Accepted)


  • 0

    0_1522903793856_b220dff1-1aba-40fb-9b26-c6badada814b-image.png

    public class Solution {
        private const int Gate = 0;
        private int[,] rooms;
        private int row;
        private int col;
        public void WallsAndGates(int[,] rooms) {
            this.rooms = rooms;
            this.row = this.rooms.GetLength(0);
            this.col = this.rooms.GetLength(1);
            for (int r = 0; r < this.row; r++)
                for (int c = 0; c < this.col; c++)  
                    if (this.rooms[r, c] == Gate)                       
                        DFS(r, c, 0);
        }    
        private void DFS(int r, int c, int distance) {
            if (r < 0 || r >= this.row || c < 0 || c >= this.col || this.rooms[r, c] < distance)
                return;
            this.rooms[r, c] = distance;
            DFS(r + 1, c, distance + 1);
            DFS(r - 1, c, distance + 1);
            DFS(r, c + 1, distance + 1);
            DFS(r, c - 1, distance + 1);
        }
    }
    

Log in to reply
 

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