MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / matrixInfection

Function matrixInfection

kotlin/Graphs/MatrixInfection.kt:1–45  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1fun matrixInfection(matrix: MutableList<MutableList<Int>>): Int {
2 val dirs = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
3 val queue = ArrayDeque<Pair<Int, Int>>()
4 var ones = 0
5 var seconds = 0
6 // Count the total number of uninfected cells and add each infected
7 // cell to the queue to represent level 0 of the level-order
8 // traversal.
9 for (r in matrix.indices) {
10 for (c in matrix[0].indices) {
11 if (matrix[r][c] == 1) {
12 ones++
13 } else if (matrix[r][c] == 2) {
14 queue.add(r to c)
15 }
16 }
17 }
18 // Use level-order traversal to determine how long it takes to
19 // infect the uninfected cells.
20 while (queue.isNotEmpty() && ones > 0) {
21 // 1 second passes with each level of the matrix that's explored.
22 seconds++
23 for (i in 0 until queue.size) {
24 val (r, c) = queue.removeFirst()
25 // Infect any neighboring 1s and add them to the queue to be
26 // processed in the next level.
27 for ((dr, dc) in dirs) {
28 val nextR = r + dr
29 val nextC = c + dc
30 if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
31 matrix[nextR][nextC] = 2
32 ones--
33 queue.add(nextR to nextC)
34 }
35 }
36 }
37 }
38 // If there are still uninfected cells left, return -1. Otherwise,
39 // return the time passed.
40 return if (ones == 0) {
41 seconds
42 } else {
43 -1
44 }
45}
46
47fun isWithinBounds(r: Int, c: Int, matrix: List<List<Int>>): Boolean {
48 return r in matrix.indices && c in matrix[0].indices

Callers

nothing calls this directly

Calls 2

isWithinBoundsFunction · 0.70
addMethod · 0.45

Tested by

no test coverage detected