codekofi
← All problems

Problem 48

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1int solution(vector<vector<int>> grid) {
2
3 if (grid.empty() || grid[0].empty()) {
4 return 0;
5 }
6
7 int rows = grid.size();
8 int cols = grid[0].size();
9
10 queue<pair<int, int>> edge;
11 int fresh = 0;
12
13 for (int r = 0; r < rows; r++) {
14 for (int c = 0; c < cols; c++) {
15
16 if (grid[r][c] == 2) {
17 edge.push({r, c});
18 }
19
20 if (grid[r][c] == 1) {
21 fresh++;
22 }
23 }
24 }
25
26 const int dr[] = {1, -1, 0, 0};
27 const int dc[] = {0, 0, 1, -1};
28
29 int steps = 0;
30
31 while (!edge.empty() && fresh > 0) {
32
33 int wide = edge.size();
34
35 for (int i = 0; i < wide; i++) {
36
37 auto [r, c] = edge.front();
38 edge.pop();
39
40 for (int d = 0; d < 4; d++) {
41
42 int nr = r + dr[d];
43 int nc = c + dc[d];
44
45 if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) {
46 continue;
47 }
48
49 if (grid[nr][nc] != 1) {
50 continue;
51 }
52
53 grid[nr][nc] = 2;
54 fresh--;
55 edge.push({nr, nc});
56 }
57 }
58
59 steps++;
60 }
61
62 if (fresh > 0) {
63 return -1;
64 }
65
66 return steps;
67}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.