
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);
}
}