[leetCode]最小體力消耗路徑
阿新 • • 發佈:2021-02-20
題目
https://leetcode-cn.com/problems/path-with-minimum-effort/
二分查詢
題目可以轉化為:
是否存在一條路徑,該路徑上的體力值不超過x,可以從左上角到達右下角
假設x = x0時存在路徑可以從左上角到達右下角,那麼當x增大時原來的路徑仍然可以使用。因此可以使用二分查詢,每次估測一個x,然後進行廣度或者深度優先搜尋,最後根據能否到達右下角來縮小搜尋範圍。
class Solution {
private int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, - 1}, {-1, 0}};
public int minimumEffortPath(int[][] heights) {
int rows = heights.length;
int cols = heights[0].length;
int left = 0, right = 999999;
int ans = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
boolean[][ ] seen = new boolean[rows][cols];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
seen[0][0] = true;
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
for (int[] dir : dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && !seen[nx][ny]
&& Math.abs(heights[x][y] - heights[nx][ny]) <= mid) {
queue.offer(new int[]{nx, ny});
seen[nx][ny] = true;
}
}
}
if (seen[rows - 1][cols - 1]) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
}
並查集
將這 rows * cols 個節點放入並查集中,實時維護它們的連通性。
由於我們需要找到從左上角到右下角的最短路徑,因此我們可以將圖中的所有邊按照權值從小到大進行排序,並依次加入並查集中。當我們加入一條權值為 x 的邊之後,如果左上角和右下角從非連通狀態變為連通狀態,那麼 x 即為答案。
class Solution {
public int minimumEffortPath(int[][] heights) {
int rows = heights.length;
int cols = heights[0].length;
List<int[]> edges = new ArrayList<>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int id = i * cols + j;
if (i > 0) {
edges.add(new int[]{id - cols, id, Math.abs(heights[i][j] - heights[i - 1][j])});
}
if (j > 0) {
edges.add(new int[]{id - 1, id, Math.abs(heights[i][j] - heights[i][j - 1])});
}
}
}
Collections.sort(edges, (o1, o2)-> o1[2]- o2[2]);
UnionFind uf = new UnionFind(rows * cols);
int ans = 0;
for (int[] edge : edges) {
int x = edge[0], y = edge[1], v = edge[2];
uf.union(x, y);
if (uf.connected(0, rows * cols - 1)) { // (r - 1) * r + c - 1
ans = v;
break;
}
}
return ans;
}
class UnionFind {
private int[] parent;
public UnionFind (int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY)
return;
parent[rootX] = rootY;
}
public boolean connected(int x, int y) {
return find(x) == find(y);
}
}
}