首先,让我们定义迪克斯特拉算法:
Dijkstra算法在具有非负边权的有向图中寻找单源最短路径.
我想知道如何使用Dijkstra算法将最短路径形式s保存到t。
我在谷歌上搜索,但找不到任何特别的东西;我也改变了Dijkstra算法,但我无法得到任何答案。如何使用Dijkstra保存从s到t的最短路径?
我知道我的问题是基本的和不专业的,但任何帮助都将不胜感激。谢谢你考虑我的问题。
发布于 2015-03-12 00:08:42
如果您查看您提供的维基百科链接中的伪码,您将在其中看到一个名为prev[]的数组。对于图中的每个节点v,该数组包含位于源节点‘s和vE 211之间最短路径上的以前的节点u。(此数组也称为前身或父数组。)
换句话说,的和v之间的最短路径是:
s -> u -> v
where u = prev[v]从的到u的路径之间可能有几个节点,因此要重建从的到v的路径,只需使用主伪码下面的代码片段(< code >E 130>目标代码>E 231是E 132ve 233)沿着prev[]数组定义的路径返回:
1 S ← empty sequence
2 u ← target
3 while prev[u] is defined: // Construct the shortest path with a stack S
4 insert u at the beginning of S // Push the vertex onto the stack
5 u ← prev[u] // Traverse from target to source
6 end while发布于 2017-12-03 05:42:14
这样做的一个非常短的方法是使用递归和“父数组”。如果将所有点的父级初始化为-1,然后在完成dijkstra时更新父数组,则可以从任意点恢复到源,并打印出路径。这里有一个非常简短且易于理解的递归片段:
// Function to print shortest path from source to j using parent array
void path(parent array, int j)
{
// Base Case : If j is source
if (jth element of parent is -1) return;
path(parent, jth element of parent);
print j;
}请注意,与打印"j“out不同,您可以将其存储在全局向量(或与C无关的语言的其他数据类型)中,供以后使用。
发布于 2021-08-20 09:04:42
只是一个修改表单那里
# define INF 0x3f3f3f3f
// iPair ==> Integer Pair
typedef pair<int, int> iPair;
void addEdge(vector <pair<int, int> > adj[], int u, int v, int wt)
{
adj[u].push_back(make_pair(v, wt));
adj[v].push_back(make_pair(u, wt));
}
void shortestPath(vector<pair<int, int> > adj[], int V, int src, int target)
{
priority_queue< iPair, vector <iPair>, greater<iPair> > pq;
vector<int> dist(V, INF);
vector<bool> visited(V, false);
vector<int> prev(V, -1);
pq.push(make_pair(0, src));
dist[src] = 0;
while (!pq.empty() && !visited[target])
{
int u = pq.top().second;
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
for (auto x : adj[u])
{
int v = x.first;
int weight = x.second;
if (dist[v] > dist[u] + weight)
{
//relax
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
prev[v] = u;
}
}
}
vector<int> res;
res.push_back(target);
int temp = target;
while (temp != 0)
{
temp = prev[temp];
res.push_back(temp);
}
//cout << res;
}
int main()
{
const int V = 9;
vector<iPair > adj[V];
addEdge(adj, 0, 1, 4);
addEdge(adj, 0, 7, 8);
addEdge(adj, 1, 2, 8);
addEdge(adj, 1, 7, 11);
addEdge(adj, 2, 3, 7);
addEdge(adj, 2, 8, 2);
addEdge(adj, 2, 5, 4);
addEdge(adj, 3, 4, 9);
addEdge(adj, 3, 5, 14);
addEdge(adj, 4, 5, 10);
addEdge(adj, 5, 6, 2);
addEdge(adj, 6, 7, 1);
addEdge(adj, 6, 8, 6);
addEdge(adj, 7, 8, 7);
shortestPath(adj, V, 0, 6); //the last one means target
return 0;
}https://stackoverflow.com/questions/28998597
复制相似问题