您的位置:首页 > 其它

286. Walls and Gates

2016-03-14 05:22 302 查看
You are given a m x n 2D grid initialized with these three possible values.
-1
- A wall or an obstacle.
0
- A gate.
INF
- Infinity means an empty room. We use the value
231 - 1 = 2147483647
to represent
INF
as you may assume that the distance to a gate is less than
2147483647
.Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with
INF
.For example, given the 2D grid:
INF-10INF
INFINFINF-1
INF-1INF-1
0-1INFINF
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
Similar:130. Surrounded Regions200. Number of Islands317. Shortest Distance from All Buildings
public class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms.length == 0 || rooms[0].length==0)
return;
Queue<int[]> queue = new LinkedList<int[]>();
int m = rooms.length;
int n = rooms[0].length;
int[] shift = {1, 0, -1, 0, 1};
for (int i=0; i<m; i++)
for (int j=0; j<n; j++) {
if (rooms[i][j] == 0) {
queue.offer(new int[] {i,j});
}
}
int level = 1;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
int[] pt = queue.poll();
// rooms[pt[0]][pt[1]] = level;
for (int k = 0; k < 4; k++) {
int r = pt[0] + shift[k];
int c = pt[1] + shift[k+1];
if (r>=0 && r<m && c>=0 && c<n && rooms[r][c] == Integer.MAX_VALUE) {
rooms[r][c] = level; // set here in case point [1][1] would put [1][0] in the queue Twice
queue.offer(new int[] {r,c});
}
}
size--;
}
level++;
}
return;
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: