-1
- A wall or an obstacle.0
- A gate.INF
- Infinity means an empty room. We use the value231 - 1 = 2147483647
to representINF
as you may assume that the distance to a gate is less than2147483647
.
INF
.For example, given the 2D grid:
INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
public class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.length == 0 || rooms[0].length == 0) return;
LinkedList<int[]> queue = new LinkedList<>();
int m = rooms.length;
int n = rooms[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (rooms[i][j] == 0) {
queue.add(new int[] {i, j});
}
}
}
int dis = 0;
while (!queue.isEmpty()) {
int count = queue.size();
while (count-- > 0) {
int[] p = queue.poll();
int x = p[0];
int y = p[1];
if (x - 1 >= 0 &&rooms[x - 1][y] == Integer.MAX_VALUE) {
rooms[x-1][y] = dis + 1;
queue.add(new int[] {x - 1, y});
}
if (x + 1 < m && rooms[x+1][y] == Integer.MAX_VALUE) {
rooms[x+1][y] = dis + 1;
queue.add(new int[] {x+1, y});
}
if (y - 1 >= 0 && rooms[x][y-1] == Integer.MAX_VALUE) {
rooms[x][y-1] = dis + 1;
queue.add(new int[] {x, y - 1});
}
if (y + 1 < n && rooms[x][y + 1] == Integer.MAX_VALUE) {
rooms[x][y+1] = dis + 1;
queue.add(new int[] {x, y + 1});
}
}
dis++;
}
}
}
没有评论:
发表评论