题目链接:找出最安全路径
题解:多源BFS + dijkstra
1. 定义dis[x][y]为从(0, 0)到(x, y)的最大安全系数
2. 因为dis[x][y]满足单调性(单调不增),就相当于最短路模型中所有边权非正,所以可以使用dijkstra算法
3. 状态转移时我们需要知道每个单元格的安全系数,而由安全系数的定义,我们可以同时从所有小偷单元格进行搜索(多源BFS),每个单元格均会被离它最近的小偷单元格搜索到
多源BFS的时间复杂度为O(n^2),dijkstra的时间复杂度为O(n^2 * logn)
代码示例:
class Solution {
public:
#define INF 1000000000
#define x first
#define y second
#define prii pair<int, int>
int maximumSafenessFactor(vector<vector<int>>& grid) {
int dx[4]{ 0,0,-1,1 }, dy[4]{ 1,-1,0,0 };
int n = grid.size();
vector<vector<int>>near(n, vector<int>(n, INF)), dis(n, vector<int>(n, 0));
queue<prii> qu;
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) {
near[i][j] = 0;
qu.emplace(i, j);
}
while (qu.size()) {
auto [ux, uy] = qu.front();
qu.pop();
for (int i = 0; i < 4; ++i) {
int nx = ux + dx[i], ny = uy + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && near[nx][ny] == INF) {
near[nx][ny] = near[ux][uy] + 1;
qu.emplace(nx, ny);
}
}
}
dis[0][0] = near[0][0];
auto cpr = [&dis](prii& a, prii& b)->bool {
return dis[a.x][a.y] < dis[b.x][b.y];
};
priority_queue<prii, vector<prii>, decltype(cpr)> hp(cpr);
hp.emplace(0, 0);
vector<bool> vis(n * n, 0);
while (hp.size()) {
auto [ux, uy] = hp.top();
hp.pop();
if (vis[ux * n + uy]) continue;
vis[ux * n + uy] = 1;
for (int i = 0; i < 4; ++i) {
int nx = ux + dx[i], ny = uy + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && !vis[nx * n + ny] && grid[nx][ny] != 1) {
int tmp = min(dis[ux][uy], near[nx][ny]);
if (tmp > dis[nx][ny]) {
dis[nx][ny] = tmp;
hp.emplace(nx, ny);
}
}
}
}
return dis[n - 1][n - 1];
}
};