codekofi
← All problems

Problem 40

Hard

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 walk(const vector<vector<int>>& grid, int r, int c,
2 vector<vector<int>>& memo) {
3
4 if (memo[r][c]) {
5 return memo[r][c];
6 }
7
8 int rows = grid.size();
9 int cols = grid[0].size();
10
11 const int dr[] = {1, -1, 0, 0};
12 const int dc[] = {0, 0, 1, -1};
13
14 int best = 1;
15
16 for (int d = 0; d < 4; d++) {
17
18 int nr = r + dr[d];
19 int nc = c + dc[d];
20
21 if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) {
22 continue;
23 }
24
25 if (grid[nr][nc] <= grid[r][c]) {
26 continue;
27 }
28
29 int longer = 1 + walk(grid, nr, nc, memo);
30 best = max(best, longer);
31 }
32
33 memo[r][c] = best;
34 return best;
35}
36
37int solution(const vector<vector<int>>& grid) {
38
39 if (grid.empty() || grid[0].empty()) {
40 return 0;
41 }
42
43 int rows = grid.size();
44 int cols = grid[0].size();
45
46 vector<vector<int>> memo(rows, vector<int>(cols, 0));
47 int ans = 0;
48
49 for (int r = 0; r < rows; r++) {
50 for (int c = 0; c < cols; c++) {
51 ans = max(ans, walk(grid, r, c, memo));
52 }
53 }
54
55 return ans;
56}

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.