迪杰斯特拉(Dijkstra)最短路径算法C++实现
前言
算法参考:《大话数据结构》
一、图的结构
使用邻接表来保存顶点之间连接的信息
二、C++实现
代码如下(示例):
#pragma once
#include <vector>
#include <string>
/*
*brief \邻接表的连接两个顶点的边
*param \
*/
struct ArcNode
{
// 边的信息
int weight = 0; // 权重
// ...
int vexIndex = -1; // 边指向的顶点的索引
ArcNode* next = nullptr; // 指向的下一条边
ArcNode(int weight, int vertexIndex, ArcNode* node = nullptr)
: weight(weight),
vexIndex(vertexIndex),
next(node)
{
}
};
/*
*brief \邻接表的顶点信息
*param \
*/
struct Vertex
{
std::string data; // 顶点信息
int in = 0; // 顶点入度
ArcNode* first = nullptr; // 指向的第一条边
Vertex() {
}
Vertex(const std::string& d, int in, ArcNode* arc = nullptr)
: data(d),
in(in),
first(arc)
{
}
// 插入边(头插法)
void insertArc(ArcNode* node)
{
node->next = first;
first = node;
}
};
/*
*brief \邻接表
*param \
*/
struct ALGraph
{
int arcNum = 0; // 边数量
int vertexNum = 0; // 顶点数量
std::vector<Vertex> vertices;
};
/*
*brief \最短路径算法: 迪杰斯特拉
*param \
*/
class ShortestPath
{
public:
ShortestPath(int vexNum, int arcNum, const std::vector<Vertex>& vertices)
{
m_alGraph.arcNum = arcNum;
m_alGraph.vertexNum = vexNum;
m_alGraph.vertices = vertices;
}
// 求v0顶点到任意顶点的最短路径
void Dijkstra