求助,关于最短路径问题
求助,自己按无权图的最短路径的代码,写了个带权图的最短路径。我写的Dijkstra的不同,我是用类似于BFS实现的。但在网上找不到和我相似的代码,所以想问一下我写的代码正确吗?已经用过多组数据测试过了,没有发现问题。
#include <cstdio>
#include <iostream>
#include <queue>
const int INF = 0x3f3f3f3f;
struct Edge {
int v1, v2;
int weight;
};
struct AdjVNode {
int adjVer;
int weight;
AdjVNode *next;
};
struct VNode {
AdjVNode *firstEdge;
};
struct LGraph {
int verNum;
int edgeNum;
VNode *G;
};
LGraph *createLGraph();
void insert(LGraph *Graph, Edge *edge);
int *shortestPath(LGraph *Graph, int src);
int main() {
LGraph *Graph = createLGraph();
int *path = shortestPath(Graph, 0);
return 0;
}
LGraph *createLGraph() {
int n, m;
scanf("%d %d", &n, &m);
LGraph *Graph = new LGraph;
Graph->verNum = n;
Graph->edgeNum = m;
Graph->G = new VNode[n];
for (int v = 0; v < n; v++) {
Graph->G[v].firstEdge = NULL;
}
for (int i = 0; i < m; i++) {
Edge *edge = new Edge;
scanf("%d %d %d", &edge->v1, &edge->v2, &edge->weight);
insert(Graph, edge);
delete edge;
}
return Graph;
}
void insert(LGraph *Graph, Edge *edge) {
AdjVNode *adjV = new AdjVNode;
adjV->adjVer = edge->v2 - 1;
adjV->weight = edge->weight;
adjV->next = Graph->G[edge->v1 - 1].firstEdge;
Graph->G[edge->v1 - 1].firstEdge = adjV;
}
int *shortestPath(LGraph *Graph, int src) {
int dist[Graph->verNum], *path = new int[Graph->verNum];
std::fill(dist, dist + Graph->verNum, INF);
std::fill(path, path + Graph->verNum, -1);
dist[src] = 0;
std::queue<int> q;
q.push(src);
while(!q.empty()) {
int v = q.front();
q.pop();
AdjVNode *w = Graph->G[v].firstEdge;
while (w) {
if (dist[v] + w->weight < dist[w->adjVer]) {
dist[w->adjVer] = dist[v] + w->weight;
path[w->adjVer] = v;
q.push(w->adjVer);
}
w = w->next;
}
}
for (int v = 0; v < Graph->verNum; v++) {
printf("%-3d", dist[v]);
}
putchar('\n');
for (int v = 0; v < Graph->verNum; v++) {
printf("%-3d", path[v] + 1);
}
return path;
}
我是用邻接表实现的。麻烦给位大神看一下。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论