LeetCode 1368. 使网格图至少有一条有效路径的最小代价
思路 : 箭头方向和搜索方向相同,代价为0, 不同代价为1
Dijkstra
const int N = 110;
typedef array<int, 3> AI3; // 表示cost,x, y
class Solution {
public:
int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
vector<vector<int>> g;
bool st[N][N] = {false};
int dijkstra()
{
int n = g.size(), m = g[0].size();
priority_queue<AI3, vector<AI3>, greater<AI3>> heap;
heap.push({0, 0, 0});
while(!heap.empty())
{
auto[c, x, y] = heap.top();
heap.pop();
if(st[x][y]) continue;
if(x == n - 1 && y == m - 1) return c;
st[x][y] = true;
for(int i = 1; i <= 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]) continue;
if(i == g[x][y]) // 方向与箭头方向相同
heap.push({c, a, b});
else
heap.push({c + 1, a, b});
}
}
return -1;
}
int minCost(vector<vector<int>>& grid) {
g = grid;
return dijkstra();
}
};
0 - 1 BFS
const int N = 110, M = N * N;
typedef pair<int, int> PII; // 表示x, y
class Solution {
public:
int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
vector<vector<int>> g;
bool st[N][N] = {false};
int dist[N][N];
int get(int x)
{
return (x + M) % M;
}
int bfs() // 0-1 BFS ,优化dijkstra
{
memset(dist, 0x3f, sizeof dist);
int n = g.size(), m = g[0].size();
PII q[M]; int tt = 0, hh = 0;
q[tt ++] = {0, 0};
dist[0][0] = 0;
while(hh != tt)
{
auto[x, y] = q[hh];
hh = get(hh + 1);
if(st[x][y]) continue;
if(x == n - 1 && y == m - 1) return dist[x][y];
st[x][y] = true;
for(int i = 1; i <= 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]) continue;
if(dist[a][b] < dist[x][y] + (i != g[x][y])) continue;
if(i == g[x][y]) // 方向与箭头方向相同
hh = get(hh - 1), q[hh] = {a, b}, dist[a][b] = dist[x][y];
else
q[tt] = {a, b}, dist[a][b] = dist[x][y] + 1, tt = get(tt + 1);
}
}
return -1;
}
int minCost(vector<vector<int>>& grid) {
g = grid;
return bfs();
}
};