codekofi
← All problems

Problem 114

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 solution(const vector<vector<int>>& grid) {
2
3 int n = grid.size();
4
5 if (n == 0) {
6 return 0;
7 }
8
9 vector<vector<bool>> seen(n, vector<bool>(n, false));
10
11 using Step = tuple<int, int, int>;
12 priority_queue<Step, vector<Step>, greater<Step>> heap;
13
14 heap.push({grid[0][0], 0, 0});
15 seen[0][0] = true;
16
17 const int dr[] = {1, -1, 0, 0};
18 const int dc[] = {0, 0, 1, -1};
19
20 while (!heap.empty()) {
21
22 auto [level, r, c] = heap.top();
23 heap.pop();
24
25 if (r == n - 1 && c == n - 1) {
26 return level;
27 }
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 >= n || nc < 0 || nc >= n) {
35 continue;
36 }
37
38 if (seen[nr][nc]) {
39 continue;
40 }
41
42 seen[nr][nc] = true;
43
44 int worst = max(level, grid[nr][nc]);
45 heap.push({worst, nr, nc});
46 }
47 }
48
49 return -1;
50}

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.