codekofi
← All problems

Problem 150

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

1vector<vector<int>> solution(vector<vector<int>> grid) {
2
3 if (grid.empty() || grid[0].empty()) {
4 return grid;
5 }
6
7 int rows = grid.size();
8 int cols = grid[0].size();
9
10 queue<pair<int, int>> edge;
11
12 for (int r = 0; r < rows; r++) {
13 for (int c = 0; c < cols; c++) {
14
15 if (grid[r][c] == 0) {
16 edge.push({r, c});
17 }
18 }
19 }
20
21 const int dr[] = {1, -1, 0, 0};
22 const int dc[] = {0, 0, 1, -1};
23
24 while (!edge.empty()) {
25
26 auto [r, c] = edge.front();
27 edge.pop();
28
29 for (int d = 0; d < 4; d++) {
30
31 int nr = r + dr[d];
32 int nc = c + dc[d];
33
34 if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) {
35 continue;
36 }
37
38 if (grid[nr][nc] != INT_MAX) {
39 continue;
40 }
41
42 grid[nr][nc] = grid[r][c] + 1;
43 edge.push({nr, nc});
44 }
45 }
46
47 return grid;
48}

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.