codekofi
← All problems

Problem 59

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

1void climb(const vector<vector<int>>& grid, int r, int c,
2 int from, vector<vector<bool>>& seen) {
3
4 int rows = grid.size();
5 int cols = grid[0].size();
6
7 if (r < 0 || r >= rows || c < 0 || c >= cols) {
8 return;
9 }
10
11 if (seen[r][c] || grid[r][c] < from) {
12 return;
13 }
14
15 seen[r][c] = true;
16
17 int here = grid[r][c];
18
19 climb(grid, r + 1, c, here, seen);
20 climb(grid, r - 1, c, here, seen);
21 climb(grid, r, c + 1, here, seen);
22 climb(grid, r, c - 1, here, seen);
23}
24
25vector<vector<int>> solution(const vector<vector<int>>& grid) {
26
27 if (grid.empty() || grid[0].empty()) {
28 return {};
29 }
30
31 int rows = grid.size();
32 int cols = grid[0].size();
33
34 vector<vector<bool>> near(rows, vector<bool>(cols, false));
35 vector<vector<bool>> far(rows, vector<bool>(cols, false));
36
37 for (int c = 0; c < cols; c++) {
38 climb(grid, 0, c, INT_MIN, near);
39 climb(grid, rows - 1, c, INT_MIN, far);
40 }
41
42 for (int r = 0; r < rows; r++) {
43 climb(grid, r, 0, INT_MIN, near);
44 climb(grid, r, cols - 1, INT_MIN, far);
45 }
46
47 vector<vector<int>> ans;
48
49 for (int r = 0; r < rows; r++) {
50 for (int c = 0; c < cols; c++) {
51
52 if (near[r][c] && far[r][c]) {
53 ans.push_back({r, c});
54 }
55 }
56 }
57
58 return ans;
59}

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.