Solution
- 从每个gate出发,对其上下左右的INF用DFS求其distance深度。
- 起始distance == 0, 每进一次,distance + 1
- base case 1: row & col Out of Bound
- base case2: 保证是最小的distance,且避开gate 和 wall。
// ensure the min distance, and avoid wall and gate as well because distance is start from 1, wall value is -1, gate is 0
if (rooms [row][col] < distance)
return;
代码
class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.length == 0 || rooms [0].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) {
wallsAndGatesHelper (rooms, i, j, 0); //distance from gate to INF
}
}
}
}
public void wallsAndGatesHelper (int[][] rooms, int row, int col, int distance) {
// out of bound
if (row < 0 || row >= rooms.length || col < 0 || col >= rooms[0].length)
return;
// ensure the min distance, and avoid wall and gate as well because distance is start from 1, wall value is -1, gate is 0
if (rooms [row][col] < distance)
return;
int[][] directions = {{1, 0},{0, 1},{-1, 0},{0, -1}};
rooms [row][col] = distance;
for (int[] direction : directions) {
wallsAndGatesHelper (rooms, row + direction [0], col + direction [1], distance + 1);
}
}
}
网友评论