难度:中等。
好的,这个题我不会。
参考官方题解https://leetcode-cn.com/problems/path-with-minimum-effort/solution/zui-xiao-ti-li-xiao-hao-lu-jing-by-leetc-3q2j/
二分法
正确解法:
class Solution {
static constexpr int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int m = heights.size(), n = heights[0].size();
int left = 0, right = 999999, result = 0;
while(left <= right){
int mid = (left + right) / 2;
queue<pair<int, int>> q;
q.emplace(0, 0);
vector<int> is_seen(m * n);
is_seen[0] = 1;
while(!q.empty()){
auto [x, y] = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int nx = x + dirs[i][0];
int ny = y + dirs[i][1];
if(nx >= 0 && nx < m && ny >= 0 && ny < n && abs(heights[x][y] - heights[nx][ny]) <= mid && is_seen[nx * n + ny] == 0){
q.emplace(nx, ny);
is_seen[nx * n + ny] = 1;
}
}
}
if(is_seen[m * n - 1]){
result = mid;
right = mid - 1;
}
else{
left = mid + 1;
}
}
return result;
}
};
并查集
class unionfindSet{
public:
vector<int> parents;
unionfindSet(int n):parents(vector<int> (n)){
for(int i = 0; i < n; i++){
parents[i] = i;
}
}
int find_root(int x){
return parents[x] == x?x:parents[x] = find_root(parents[x]);
}
void merge(int x, int y){
int rootx = find_root(x);
int rooty = find_root(y);
if(rootx != rooty){
parents[rooty] = rootx;
}
}
bool connected(int x, int y){
int rootx = find_root(x);
int rooty = find_root(y);
return rootx == rooty;
}
};
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int m = heights.size(), n = heights[0].size();
vector<tuple<int, int, int>> edges;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int a = i * n + j;
if(i < m - 1){
int b = a + n;
int weight = abs(heights[i][j] - heights[i + 1][j]);
edges.emplace_back(a, b, weight);
}
if(j < n - 1){
int b = a + 1;
int weight = abs(heights[i][j] - heights[i][j + 1]);
edges.emplace_back(a, b, weight);
}
}
}
sort(edges.begin(), edges.end(), [](const auto& e1, const auto& e2){
auto&& [x1, y1, v1] = e1;
auto&& [x2, y2, v2] = e2;
return v1 < v2;
});
unionfindSet uf(m * n);
for(const auto [x, y, v]: edges){
uf.merge(x, y);
if(uf.connected(0, m * n - 1)){
return v;
}
}
return 0;
}
};
最短路径
不想思考了,累了。