Approach
We re-create the graph with edge weight doubled for reverse direction, and then do BFS-like to find the minimum approaching results, but there are no guarantee for hte time complexity, instead we should apply the dijkstra like approach to get the .
Code-1: BFS like (no time complexity guarantee)
class Solution {
public:
int minCost(int n, vector<vector<int>>& edges) {
vector<vector<pair<int, int>>> adj(n);
for(const auto& e: edges) {
adj[e[0]].push_back({e[1], e[2]});
adj[e[1]].push_back({e[0], 2*e[2]});
}
vector<int> minCost(n, INT_MAX);
queue<pair<int,int>> q; // idx, cost
q.push({0,0});
while(!q.empty()) {
auto [idx, cost] = q.front();
q.pop();
if(cost >= minCost[idx]) continue;
minCost[idx] = cost;
for(const auto& [next, w]: adj[idx]) {
q.push({next, cost+w});
}
}
return minCost[n-1] == INT_MAX ? -1 : minCost[n-1];
}
};
Code-2: Dijkstra like approach
class Solution {
public:
int minCost(int n, vector<vector<int>>& edges) {
vector<vector<pair<int, int>>> adj(n);
for(const auto& e: edges) {
adj[e[0]].push_back({e[1], e[2]});
adj[e[1]].push_back({e[0], 2*e[2]});
}
vector<int> minCost(n, INT_MAX);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq; // cost, idx
pq.push({0, 0});
minCost[0] = 0;
while(!pq.empty()) {
auto [cost, idx] = pq.top();
pq.pop();
if(minCost[idx] != cost) continue; // outdated
if(idx == n - 1) break;
for(const auto& [next, w]: adj[idx]) {
if(cost + w < minCost[next]) {
minCost[next] = cost + w;
pq.push({cost+w, next});
}
}
}
return minCost[n-1] == INT_MAX ? -1 : minCost[n-1];
}
};