Practice › Graphs
Swim in Rising Water
Hard · Graphs · Asked at Google, Amazon, Microsoft
An n × n grid holds the elevation of each cell; the values are a permutation of 0 … n² − 1. At time t the water level everywhere is t, and you may move up, down, left or right between two cells only if both elevations are at most t (moving takes no time). Starting at the top-left cell, print the least time at which you can reach the bottom-right cell.
Input
First line: n. Next n lines: n integers each.
Output
The minimum time.
Constraints
- 1 ≤ n ≤ 150
- the values are a permutation of 0 … n² − 1
The time needed for a path is the largest elevation on it, so minimise the maximum. A Dijkstra-like search with a min-heap keyed by "highest elevation so far" works, as does a binary search on t with a BFS check.
Example 1
Input
2 0 2 1 3
Output
3
Example 2
Input
5 0 1 2 3 4 24 23 22 21 5 12 13 14 15 16 11 17 18 19 20 10 9 8 7 6
Output
16
Hints
- A path can be used at time t exactly when its highest cell is at most t.
- So you want the path from corner to corner whose maximum elevation is smallest.
- Dijkstra works with "max so far" in place of "sum so far".
Approach
Run a Dijkstra-style search from (0, 0) where the cost of a cell is the largest elevation on the best path to it: cost(next) = max(cost(cur), elevation(next)). A min-heap pops cells in increasing cost, so the first time the bottom-right cell is popped, its cost is the answer. (Alternatives: binary search on t with BFS, or adding cells in order of elevation to a DSU until the corners connect.)
Complexity: O(n² log n) time · O(n²) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> g(n, vector<int>(n));
for (auto &row : g)
for (auto &x : row) cin >> x;
vector<vector<bool>> seen(n, vector<bool>(n, false));
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq;
pq.push({g[0][0], 0, 0});
seen[0][0] = true;
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
while (!pq.empty()) {
auto _b = pq.top();
auto t = get<0>(_b);
auto x = get<1>(_b);
auto y = get<2>(_b);
pq.pop();
if (x == n - 1 && y == n - 1) {
cout << t << "\n";
return 0;
}
for (int d = 0; d < 4; d++) {
int a = x + dx[d], b = y + dy[d];
if (a >= 0 && b >= 0 && a < n && b < n && !seen[a][b]) {
seen[a][b] = true;
pq.push({max(t, g[a][b]), a, b});
}
}
}
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
g = [data[1 + i * n : 1 + (i + 1) * n] for i in range(n)]
seen = [[False] * n for _ in range(n)]
seen[0][0] = True
pq = [(g[0][0], 0, 0)]
while pq:
t, x, y = heapq.heappop(pq)
if x == n - 1 and y == n - 1:
print(t)
break
for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if 0 <= a < n and 0 <= b < n and not seen[a][b]:
seen[a][b] = True
heapq.heappush(pq, (max(t, g[a][b]), a, b))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[][] g = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
in.nextToken();
g[i][j] = (int) in.nval;
}
boolean[][] seen = new boolean[n][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.add(new int[] {g[0][0], 0, 0});
seen[0][0] = true;
int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
while (!pq.isEmpty()) {
int[] c = pq.poll();
if (c[1] == n - 1 && c[2] == n - 1) {
System.out.println(c[0]);
return;
}
for (int d = 0; d < 4; d++) {
int a = c[1] + dx[d], b = c[2] + dy[d];
if (a >= 0 && b >= 0 && a < n && b < n && !seen[a][b]) {
seen[a][b] = true;
pq.add(new int[] {Math.max(c[0], g[a][b]), a, b});
}
}
}
}
}