Skip to content

Commit 8f239f6

Browse files
committed
add: MatrixInfection
1 parent f08e78f commit 8f239f6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

java/Graphs/MatrixInfection.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import java.util.ArrayDeque;
2+
import java.util.Deque;
3+
4+
public class MatrixInfection {
5+
public int matrixInfection(int[][] matrix) {
6+
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
7+
Deque<int[]> queue = new ArrayDeque<>();
8+
int ones, seconds;
9+
ones = seconds = 0;
10+
// Count the total number of uninfected cells and add each infected
11+
// cell to the queue to represent level 0 of the level-order
12+
// traversal.
13+
for (int r = 0; r < matrix.length; r++) {
14+
for (int c = 0; c < matrix[0].length; c++) {
15+
if (matrix[r][c] == 1) {
16+
ones += 1;
17+
} else if (matrix[r][c] == 2) {
18+
queue.offer(new int[]{r, c});
19+
}
20+
}
21+
}
22+
// Use level-order traversal to determine how long it takes to
23+
// infect the uninfected cells.
24+
while (!queue.isEmpty() && ones > 0) {
25+
// 1 second passes with each level of the matrix that's explored.
26+
seconds++;
27+
int size = queue.size();
28+
for (int i = 0; i < size; i++) {
29+
int[] pos = queue.poll();
30+
int r = pos[0];
31+
int c = pos[1];
32+
// Infect any neighboring 1s and add them to the queue to be
33+
// processed in the next level.
34+
for (int[] d : dirs) {
35+
int nextR = r + d[0];
36+
int nextC = c + d[1];
37+
if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
38+
matrix[nextR][nextC] = 2;
39+
ones--;
40+
queue.offer(new int[]{nextR, nextC});
41+
}
42+
}
43+
}
44+
}
45+
// If there are still uninfected cells left, return -1. Otherwise,
46+
// return the time passed.
47+
return ones == 0 ? seconds : -1;
48+
}
49+
50+
private boolean isWithinBounds(int r, int c, int[][] matrix) {
51+
return 0 <= r && r < matrix.length && 0 <= c && c < matrix[0].length;
52+
}
53+
}

0 commit comments

Comments
 (0)