Given a 2D grid, each cell is either a wall 2
, a zombie 1
or people 0
(the number zero, one, two).Zombies can turn the nearest people(up/down/left/right) into zombies every day, but can not through wall. How long will it take to turn all people into zombies? Return -1
if can not turn all people into zombies.
Example
Example 1:
Input:
[[0,1,2,0,0],
[1,0,0,2,1],
[0,1,0,0,0]]
Output:
2
Example 2:
Input:
[[0,0,0],
[0,0,0],
[0,0,1]]
Output:
4
思路:所有的zombie 也就是grid[i][j] =1的点为一层,同时开始往外扩散;相当于一层一层的扩散;别忘记最后step空+1,要减去1
public class Solution {
/**
* @param grid: a 2D integer grid
* @return: an integer
*/
public int zombie(int[][] grid) {
// BFS;
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
boolean[][] visited = new boolean[n][m];
Queue<int[]> queue = new LinkedList<int[]>();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 1) {
queue.offer(new int[]{i, j});
}
}
}
int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
visited[node[0]][node[1]] = true;
for(int[] dir: dirs) {
int nx = node[0] + dir[0];
int ny = node[1] + dir[1];
if(0 <= nx && nx < n && 0 <= ny && ny < m
&& !visited[nx][ny] && grid[nx][ny] != 2 && grid[nx][ny] == 0) {
grid[nx][ny] = 1;
queue.offer(new int[]{nx, ny});
}
}
}
step++;
}
boolean allone = true;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 0) {
allone = false;
}
}
}
return allone == false ? -1 : step - 1;
}
}