-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathZombieinMatrix.java
89 lines (77 loc) · 2.33 KB
/
ZombieinMatrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Solution {
public int PEOPLE = 0;
public int ZOMBIE = 1;
public int WALL = 2;
public int[] deltaX = {1, 0, 0, -1};
public int[] deltaY = {0, 1, -1, 0};
/**
* @param grid a 2D integer grid
* @return an integer
*/
public int zombie(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
// initialize the queue & count people
int people = 0;
Queue<Coordinate> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == PEOPLE) {
people++;
} else if (grid[i][j] == ZOMBIE) {
queue.offer(new Coordinate(i, j));
}
}
}
// corner case
if (people == 0) {
return 0;
}
// bfs
int days = 0;
while (!queue.isEmpty()) {
days++;
int size = queue.size();
for (int i = 0; i < size; i++) {
Coordinate zb = queue.poll();
for (int direction = 0; direction < 4; direction++) {
Coordinate adj = new Coordinate(
zb.x + deltaX[direction],
zb.y + deltaY[direction]
);
if (!isPeople(adj, grid)) {
continue;
}
grid[adj.x][adj.y] = ZOMBIE;
people--;
if (people == 0) {
return days;
}
queue.offer(adj);
}
}
}
return -1;
}
private boolean isPeople(Coordinate coor, int[][] grid) {
int n = grid.length;
int m = grid[0].length;
if (coor.x < 0 || coor.x >= n) {
return false;
}
if (coor.y < 0 || coor.y >= m) {
return false;
}
return (grid[coor.x][coor.y] == PEOPLE);
}
}