1 题目
Given a matrix of integers A
with R rows and C columns, find the maximum score of a path starting at [0,0]
and ending at [R-1,C-1]
.
The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.
A path moves some number of times from one visited cell to any neighbouring unvisited cell in one of the 4 cardinal directions (north, east, west, south).
Example 1:
Input: [[5,4,5],[1,2,6],[7,4,6]]
Output: 4
Explanation:
The path with the maximum score is highlighted in yellow.
Example 2:
Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]]
Output: 2
Example 3:
Input: [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
Output: 3
2 尝试解
2.1 分析
从左上角到右下角的任意路径,用该路径上所有元素的最小值作为该路径的成本,求最大成本路径。
用类似Dijstra算法,从起点出发,将当前所有已到达位置的可达且未访问过的位置统一加入堆中,每次取出堆顶元素作为下一个要访问的位置。直到终点被访问到停止算法。
2.2 代码
class Solution {
public:
int maximumMinimumPath(vector<vector<int>>& A) {
set<pair<int,int>> visited;
priority_queue<pair<int,pair<int,int>>> candidates;
candidates.push(make_pair(A[0][0],make_pair(0,0)));
int result = INT_MAX;
while(visited.count(make_pair(A.size()-1,A[0].size()-1))==0){
result = min(candidates.top().first,result);
auto coor = candidates.top().second;
candidates.pop();
visited.insert(coor);
vector<pair<int,int>> neighbor{{coor.first-1,coor.second},{coor.first+1,coor.second},{coor.first,coor.second-1},{coor.first,coor.second+1}};
for(auto n:neighbor){
if(visited.count(n) == 0 &&n.first >= 0 && n.first<A.size()&&n.second>=0 && n.second < A[0].size()){
candidates.push(make_pair(A[n.first][n.second],n));
}
}
}
return result;
}
};
3 标准解
3.1 分析
用UnionFind算法,将所有位置按照值排序,每次访问堆顶元素,如果该位置的四连通邻居已经被访问过,则将二者合并,直到起止点相连。
3.2 代码
class Solution {
public:
int maximumMinimumPath(vector<vector<int>>& A) {
const int M = A.size();
const int N = A[0].size();
const int X = M * N;
parent = vector<int>(X, 0);
for (int i = 0; i < parent.size(); ++i)
parent[i] = i;
vector<vector<int>> values;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
values.push_back({A[i][j], i, j});
}
}
sort(values.begin(), values.end(), [](vector<int>& a, vector<int>& b) {return a[0] < b[0];});
unordered_set<int> visited;
visited.insert(0);
visited.insert(X - 1);
int res = min(A[0][0], A[M - 1][N - 1]);
while(find(0) != find(X - 1)) {
vector<int> cur = values.back(); values.pop_back();
visited.insert(cur[1] * N + cur[2]);
res = min(res, cur[0]);
for (auto& dir : dirs) {
int newx = cur[1] + dir[0];
int newy = cur[2] + dir[1];
if (newx >= 0 && newx < M && newy >= 0 && newy < N && visited.count(newx * N + newy)) {
uni(cur[1] * N + cur[2], newx * N + newy);
}
}
}
return res;
}
int find(int a) {
if (parent[a] == a)
return a;
return find(parent[a]);
}
void uni(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa == pb)
return;
parent[pa] = pb;
}
private:
vector<int> parent;
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
};