题目
给一个二维网格,每一个格子都有一个值,2 代表墙,1 代表僵尸,0 代表人类(数字 0, 1, 2)。僵尸每天可以将上下左右最接近的人类感染成僵尸,但不能穿墙。将所有人类感染为僵尸需要多久,如果不能感染所有人则返回 -1。
样例
给一个矩阵:
0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
返回 2
代码
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Solution {
/**
* @param grid a 2D integer grid
* @return an integer
*/
int PEOPLE = 0;
int ZOMBIE = 1;
int WALL = 2;
int[] detalX = {0, 0, 1, -1};
int[] detalY = {1, -1, 0, 0};
public int zombie(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0; //注意此处返回0
}
int m = grid.length;
int n = grid[0].length;
int people = 0;
Queue queue = new LinkedList<>();
// 遍历矩阵,统计人的个数,并且把僵尸的位置加入队列
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == PEOPLE) {
people++;
}
else if (grid[i][j] == ZOMBIE) {
queue.offer(new Coordinate(i, j));
}
}
}
// 注意特殊情况
if (people == 0) {
return 0;
}
int days = 0;
while (!queue.isEmpty()) {
// 分层来做,层数即天数
days++;
int size = queue.size();
for (int i = 0; i < size; i++) {
// 注意结点在第一个for里面抛出,不能写到for外面
Coordinate zb = queue.poll();
for (int direction = 0; direction < 4; direction++) {
Coordinate adj = new Coordinate(
zb.x + detalX[direction],
zb.y + detalY[direction]);
// 接口形参应该是结点和矩阵
if (!isPeople(grid, adj)) {
continue;
}
grid[adj.x][adj.y] = ZOMBIE;
people--;
if (people == 0) {
return days;
}
queue.offer(adj);
}
}
}
return -1;
}
private boolean isPeople(int[][] grid, Coordinate coor) {
int m = grid.length;
int n = grid[0].length;
if (coor.x < 0 || coor.x > m - 1) {
return false;
}
if (coor.y < 0 || coor.y > n - 1) {
return false;
}
return (grid[coor.x][coor.y] == PEOPLE);
}
}
注意经常出现error: cannot find symbol错误的原因就是后续代码没有写在for循环内部