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

Function matrixInfection

cpp/Graphs/matrix_infection.cpp:4–44  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2#include <deque>
3
4int matrixInfection(std::vector<std::vector<int>>& matrix) {
5 std::vector<std::pair<int, int>> dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
6 std::deque<std::pair<int, int>> queue;
7 int ones = 0, seconds = 0;
8 // Count the total number of uninfected cells and add each infected
9 // cell to the queue to represent level 0 of the level-order traversal.
10 for (int r = 0; r < matrix.size(); r++) {
11 for (int c = 0; c < matrix[0].size(); c++) {
12 if (matrix[r][c] == 1) {
13 ones++;
14 } else if (matrix[r][c] == 2) {
15 queue.push_back({r, c});
16 }
17 }
18 }
19 // Use level-order traversal to determine how long it takes to
20 // infect the uninfected cells.
21 while (!queue.empty() && ones > 0) {
22 // 1 second passes with each level of the matrix that's explored.
23 seconds++;
24 int size = queue.size();
25 for (int unused = 0; unused < size; unused++) {
26 auto [r, c] = queue.front();
27 queue.pop_front();
28 // Infect any neighboring 1s and add them to the queue to be
29 // processed in the next level.
30 for (auto& d : dirs) {
31 int nextR = r + d.first;
32 int nextC = c + d.second;
33 if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
34 matrix[nextR][nextC] = 2;
35 ones--;
36 queue.push_back({nextR, nextC});
37 }
38 }
39 }
40 }
41 // If there are still uninfected cells left, return -1. Otherwise,
42 // return the time passed.
43 return ones == 0 ? seconds : -1;
44}
45
46bool isWithinBounds(int r, int c, std::vector<std::vector<int>>& matrix) {
47 return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size();

Callers

nothing calls this directly

Calls 1

isWithinBoundsFunction · 0.70

Tested by

no test coverage detected