在C++中,图是一种重要的非线性数据结构,用于表示实体之间的复杂关系,不仅在项目中,在408中也是重点内容(同时也是难点内容)
本期就让我们来学习一下C++中图的数据结构
相关代码已经上传至作者的个人gitee中:楼田莉子/CPP代码学习喜欢请点个赞谢谢
目录
图的基本概念
图的存储结构
邻接矩阵
邻接表
图的遍历
广度优先遍历
深度优先遍历
递归版本
循环版本
最小生成树
Kruskal算法
Prim算法
set实现版本
vector实现版本
最短路径问题
单源最短路径–Dijkstra算法
编辑
单源最短路径–Bellman-Ford算法
编辑 多源最短路径–Floyd-Warshall算法
源码
Graph.h
UnionFindSet3.h
test1.cpp
图的基本概念
图是由顶点集合及顶点间的关系组成的一种数据结构:G = (V, E),其中:顶点集合V = {x|x属于某个数据对象集}是有穷非空集合; E = {(x,y)|x,y属于V}或者E = {<x, y>|x,y属于V && Path(x, y)}是顶点间关系的有穷集合,也叫做边的集合。(x, y)表示x到y的一条双向通路,即(x, y)是无方向的;Path(x, y)表示从x到y的一条单向通路,即Path(x, y)是有方向的。
树是一种特殊的无环连通的图,但是图不一定是树。
树关注的是节点和其存储的值;图关注的是顶点及其边的权值。
图的术语:
顶点和边:图中结点称为顶点,第i个顶点记作vi。两个顶点vi和vj相关联称作顶点vi和顶点vj之间有一条边,图中的第k条边记作ek,ek = (vi,vj)或<vi,vj>。
有向图和无向图:在有向图中,顶点对<x, y>是有序的,顶点对<x,y>称为顶点x到顶点y的一条边(弧),<x, y>和<y, x>是两条不同的边,比如下图G3和G4为有向图。在无向图中,顶点对(x, y)是无序的,顶点对(x,y)称为顶点x和顶点y相关联的一条边,这条边没有特定方向,(x, y)和(y,x)是同一条边,比如下图G1和G2为无向图。注意:无向边(x, y)等于有向边<x, y>和<y, x>。
完全图:在有n个顶点的无向图中,若有n * (n-1)/2条边,即任意两个顶点之间有且仅有一条边,则称此图为无向完全图,比如上图G1;在n个顶点的有向图中,若有n * (n-1)条边,即任意两个顶点之间有且仅有方向相反的边,则称此图为有向完全图,比如上图G4。(任意两点之间都相连,是最稠密的图)
邻接顶点:在无向图中G中,若(u, v)是E(G)中的一条边,则称u和v互为邻接顶点,并称边(u,v)依附于顶点u和v;在有向图G中,若<u, v>是E(G)中的一条边,则称顶点u邻接到v,顶点v邻接自顶点u,并称边<u, v>与顶点u和顶点v相关联。
顶点的度:顶点v的度是指与它相关联的边的条数,记作deg(v)。在有向图中,顶点的度等于该顶点的入度与出度之和,其中顶点v的入度是以v为终点的有向边的条数,记作indev(v);顶点v的出度是以v为起始点的有向边的条数,记作outdev(v)。因此:dev(v) = indev(v) + outdev(v)。
注意:对于无向图,顶点的度等于该顶点的入度和出度,即dev(v) = indev(v) = outdev(v)。
路径:在图G = (V, E)中,若从顶点vi出发有一组边使其可到达顶点vj,则称顶点vi到顶点vj的顶点序列为从顶点vi到顶点vj的路径。
路径长度:对于不带权的图,一条路径的路径长度是指该路径上的边的条数;对于带权的图,一条路径的路径长度是指该路径上各个边权值的总和。

简单路径与回路:若路径上各顶点v1,v2,v3,…,vm均不重复,则称这样的路径为简单路径。若路径上第一个顶点v1和最后一个顶点vm重合,则称这样的路径为回路或环。

子图:设图G = {V, E}和图G1 = {V1,E1},若V1属于V且E1属于E,则称G1是G的子图。

连通图:在无向图中,若从顶点v1到顶点v2有路径,则称顶点v1与顶点v2是连通的。如果图中任意一对顶点都是连通的,则称此图为连通图。 强连通图:在有向图中,若在每一对顶点vi和vj之间都存在一条从vi到vj的路径,也存在一条从vj到vi的路径,则称此图是强连通图。 生成树:一个连通图的最小连通子图称作该图的生成树。有n个顶点的连通图的生成树有n个顶点和n-1条边。
图的存储结构
因为图中既有节点,又有边(节点与节点之间的关系),因此,在图的存储中,只需要保存:节点和边关系即可。节点保存比较简单,只需要一段连续空间即可。
邻接矩阵和邻接表是图的两种存储结构。它们相辅相成各有其优缺点
邻接矩阵
因为节点与节点之间的关系就是连通与否,即为0或者1,因此邻接矩阵(二维数组)即是:先用一个数组将定点保存,然后采用矩阵来表示节点与节点之间的关系。
无向图是一个对称的矩阵。

如果我们想表示点和点之间的“权值”。比如在社会关系网络中,用来表示关系的强弱,就要使用有向图

邻接矩阵的优点:
1、邻接矩阵适合存储稠密图
2、可以以O(1)的方式判断两个顶点的连接关系并取权值。
邻接矩阵的缺点:
1、存储稀疏图体积比较大
2、不适合查找一个顶点连接的所有的边(复杂度为O(N))
源代码实现
//邻接矩阵图
namespace AMGraph
{
//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W= INT_MAX,bool direction=false>
//权值很多时候是整型
class Graph
{
public:
//图的创建
//1、IO输入(不便于测试)
//2、写入文件读取文件(不便于改)
//3、手动添加边
Graph() = default;
Graph(const V*a,size_t n)
//n为顶点
{
_vertexs.reserve(n);
for (size_t i =0;i<n;++i)
{
_vertexs.push_back(a[i]);
_IndexMap[a[i]] = i;
}
_matrix.resize(n);
for (size_t i=0;i<_matrix.size();++i)
{
_matrix[i].resize(n, MAX_W);
}
}
//确定顶点的下标
size_t GetVertexsIndex(const V&v)
{
auto it = _IndexMap.find(v);
if (it != _IndexMap.end())
{
return it->second;
}
else
{
//assert(false);
throw std::invalid_argument("定点不存在");
return -1;
}
}
//添加边
//两个顶点一个权值
void AddEdge(const V&src,const V&dst,const W&w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
_matrix[src_m][dst_m] = w;
//无向图
if (direction==false)
{
_matrix[src_m][dst_m] = w;
}
}
void Print()
{
// 顶点与下标的映射
//横下表
for (size_t i = 0; i < _vertexs.size(); ++i)
{
cout << "[" << i << "]" <<"->" << _vertexs[i] << endl;
}
cout << endl;
//矩阵
//横坐标
cout << " ";
for (size_t i = 0; i < _vertexs.size(); ++i)
{
cout << i << " ";
}
cout << endl;
for (size_t i = 0; i < _matrix.size(); ++i)
{
//纵坐标
cout << i << " ";
//矩阵
for (size_t j = 0; j < _matrix[i].size(); ++j)
{
if (_matrix[i][j] == MAX_W)
{
cout << "* ";
}
else
{
cout << _matrix[i][j] << " ";
}
}
cout << endl;
}
cout << endl;
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
邻接表
邻接表:使用数组表示顶点的集合,使用链表表示边的关系
就是使用指针数组来存储图的关系
无向图的邻接表

有向图的邻接表

邻接表的优点:
1、适合存储稀疏图
2、适合查找一个顶点连接出去的边
邻接表的缺点:
不适合确定两个顶点是否相连并确定其权值。
源代码实现:
//邻接表图
namespace ALGraph
{
//边
template<class W>
struct Edge
{
int _src;//源点的下标
int _dst;//目标点的下标
W _w;//权值
Edge<W>* _next;//链接下一个点的指针
Edge(const W& w)
: _src(-1)
, _dst(-1)
, _w(w)
, _next(nullptr)
{
}
};
//顶点 权值 是否有向
template<class V, class W, bool direction = false>
//权值很多时候是整型
class Graph
{
using GraphEdge = Edge<W>;
public:
//图的创建
//1、IO输入(不便于测试)
//2、写入文件读取文件(不便于改)
//3、手动添加边
//顶点数组构造
Graph(const V* a, size_t n)
//n为顶点
{
_vertexs.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_vertexs.push_back(a[i]);
_IndexMap[a[i]] = i;
}
_tables.resize(n, nullptr);
}
// 默认构造函数
Graph() = default;
// 列表初始化构造函数:只初始化顶点
Graph(std::initializer_list<V> vertices)
{
size_t n = vertices.size();
_vertexs.reserve(n);
size_t idx = 0;
for (const auto& vertex : vertices)
{
_vertexs.push_back(vertex);
_IndexMap[vertex] = idx++;
}
_tables.resize(n, nullptr);
}
//添加顶点
size_t AddVertex(const V& vertex)
{
auto it = _IndexMap.find(vertex);
if (it != _IndexMap.end())
{
return it->second;
}
size_t index = _vertexs.size();
_vertexs.push_back(vertex);
_IndexMap[vertex] = index;
_tables.push_back(nullptr);
return index;
}
//确定顶点的下标
size_t GetVertexsIndex(const V& v)
{
auto it = _IndexMap.find(v);
if (it != _IndexMap.end())
{
return it->second;
}
else
{
throw std::invalid_argument("顶点不存在");
}
}
//添加边
//两个顶点一个权值
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
// 创建正向边 src->dst
GraphEdge* eg = new GraphEdge(w);
eg->_src = (int)src_m;
eg->_dst = (int)dst_m;
eg->_next = _tables[src_m];
_tables[src_m] = eg;
// 如果是无向图,还需要添加反向边 dst->src
if (direction == false)
{
GraphEdge* reverse_eg = new GraphEdge(w);
reverse_eg->_src = (int)dst_m;
reverse_eg->_dst = (int)src_m;
reverse_eg->_next = _tables[dst_m];
_tables[dst_m] = reverse_eg;
}
}
void print()
{
// 顶点与下标的映射
//横下表
for (size_t i = 0; i < _vertexs.size(); ++i)
{
cout << "[" << i << "]" << "->" << _vertexs[i] << endl;
}
cout << endl;
for (size_t i = 0; i < _tables.size(); ++i)
{
cout << _vertexs[i] << "[" << i << "]" << "->";
GraphEdge* cur = _tables[i];
while (cur)
{
cout << "" << _vertexs[cur->_dst] << "[" << cur->_dst << "]" << " [权值:" << cur->_w << "]->";
cur = cur->_next;
}
cout << "nullptr" << endl;
}
cout << endl;
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<GraphEdge*> _tables;//邻接表
};
}
图的遍历
给定一个图G和其中任意一个顶点v0,从v0出发,沿着图中各边访问图中的所有顶点,且每个顶点仅被遍历一次。"遍历"即对结点进行某种操作的意思。
广度优先遍历

我们以以下这个例子来说明:
比如我们要找东西,假设有三个抽屉,东西在哪个抽屉不清楚。

广度优先遍历的做法是:
先将三个抽屉打开,在最外层找一遍
将每个抽屉中红色的盒子打开,再找一遍
将红色盒子中绿色盒子打开,再找一遍 直到找完所有的盒子,注意:每个盒子只能找一次,不能重复找。
那么我们怎么找呢?如下图所示

利用队列。将A入队列

随后将A相连的B、C、D入队列。

随后B 出队列将B周围点入队列。将已经遍历过的点入第二个队列。

这里我们会发现第一个队列有两个C。图的遍历是不允许有重复的,但是第一个C并没有被访问所以还没有去除。

至此我们需要两个东西:一个是队列,一个是标记容器。
注意:入队列就标记结点,这样可以防止像A出的时候入的BCD,像B出的时候入的ACE,那么入队列就标记了AC就不会重复入了
具体实现如下:
//邻接矩阵图
namespace AMGraph
{
//广度优先遍历
void BFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
queue<int>q;
q.push(src_m);
size_t n = _vertexs.size();
vector<bool>visited(n, false);
int levelsize = 1;
visited[src_m] = true;
cout << "从顶点 " << src << " 开始的广度优先遍历:" << endl;
while (!q.empty())
{
//一层一层出
for(size_t i=0;i<levelsize;++i)
{
int front = q.front();
q.pop();
cout << front << " : " << _vertexs[front] << endl;
//把邻接顶点入队列
for (size_t i = 0; i < n; ++i)
{
if (_matrix[front][i] != MAX_W)
{
if (visited[i] == false)
{
q.push(i);
visited[i] = true;
}
}
}
}
printf("\\n");
levelsize = q.size();
}
printf("\\n");
}
}
//邻接表图
namespace ALGraph
{
// 广度优先遍历
void BFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
queue<int> q;
q.push(src_m);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
int levelsize = 1;
visited[src_m] = true;
cout << "从顶点 " << src << " 开始的广度优先遍历:" << endl;
while (!q.empty())
{
// 一层一层出
for (size_t i = 0; i < levelsize; ++i)
{
int front = q.front();
q.pop();
cout << front << " : " << _vertexs[front] << endl;
// 把邻接顶点入队列
GraphEdge* cur = _tables[front];
while (cur)
{
if (visited[cur->_dst] == false)
{
q.push(cur->_dst);
visited[cur->_dst] = true;
}
cur = cur->_next;
}
}
printf("\\n");
levelsize = q.size();
}
printf("\\n");
}
}
测试代码:
//邻接矩阵的广度遍历
void test2()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
AMGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.BFS("歌者");
cout << endl;
g1.BFS("观察者");
cout << endl;
g1.BFS("理想者");
cout << endl;
g1.BFS("幻想者");
cout << endl;
}
//邻接表的广度遍历
void test4()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
ALGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.BFS("歌者");
cout << endl;
g1.BFS("观察者");
cout << endl;
g1.BFS("理想者");
cout << endl;
g1.BFS("幻想者");
cout << endl;
}
测试结果如下:


深度优先遍历

关于深度优先遍历, 我们以以下这个例子来说明:
比如现在要找东西,假设有三个抽屉,东西在那个抽屉不清楚,现在要将其找到,广度优先遍历的做法是:
先将第一个抽屉打开,在最外层找一遍
将第一个抽屉中红盒子打开,在红盒子中找一遍
将红盒子中绿盒子打开,在绿盒子中找一遍
递归查找剩余的两个盒子
深度优先遍历:将一个抽屉一次性遍历完(包括该抽屉中包含的小盒子),再去递归遍历其他盒子

我们来实现一下:
递归版本
//邻接矩阵图
namespace AMGraph
{
//深度优先遍历
void DFS(const V&src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool>visited(n, false);
cout << "从顶点 " << src << " 开始的深度优先遍历:" << endl;
_DFS(src_m, visited);
cout<<endl;
}
//深度优先子函数
void _DFS(size_t src_m ,vector<bool>&visited)
{
cout << src_m << " : " << _vertexs[src_m] << endl;
visited[src_m] = true;
//找src_m相邻的点去深度访问
for (size_t i=0;i<_vertexs.size();++i)
{
if (_matrix[src_m][i] != MAX_W&& visited[i] == false)
{
_DFS(i,visited);
}
}
}
}
//邻接表图
namespace ALGraph
{
// 深度优先遍历
void DFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
cout << "从顶点 " << src << " 开始的深度优先遍历:" << endl;
_DFS(src_m, visited);
cout << endl;
}
// 深度优先子函数
void _DFS(size_t src_m, vector<bool>& visited)
{
cout << src_m << " : " << _vertexs[src_m] << endl;
visited[src_m] = true;
// 找src_m相邻的点去深度访问
GraphEdge* cur = _tables[src_m];
while (cur)
{
if (visited[cur->_dst] == false)
{
_DFS(cur->_dst, visited);
}
cur = cur->_next;
}
}
}
循环版本
// 邻接矩阵图的循环DFS实现
namespace AMGraph
{
template<class V, class W, W MAX_W, bool direction>
void Graph<V, W, MAX_W, direction>::DFSIterative(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
stack<size_t> stk;
cout << "从顶点 " << src << " 开始的深度优先遍历(循环版本):" << endl;
// 将起始顶点入栈并标记访问
stk.push(src_m);
visited[src_m] = true;
cout << src_m << " : " << _vertexs[src_m] << endl;
while (!stk.empty())
{
size_t current = stk.top();
bool hasUnvisitedNeighbor = false;
// 查找当前顶点的未访问邻接点
for (size_t i = 0; i < n; ++i)
{
if (_matrix[current][i] != MAX_W && !visited[i])
{
// 找到未访问的邻接点,访问并入栈
stk.push(i);
visited[i] = true;
cout << i << " : " << _vertexs[i] << endl;
hasUnvisitedNeighbor = true;
break; // 深度优先,先深入一个分支
}
}
// 如果没有未访问的邻接点,回溯
if (!hasUnvisitedNeighbor)
{
stk.pop();
}
}
cout << endl;
}
// 另一种实现方式:在弹出时访问
template<class V, class W, W MAX_W, bool direction>
void Graph<V, W, MAX_W, direction>::DFSIterative2(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
stack<size_t> stk;
cout << "从顶点 " << src << " 开始的深度优先遍历(循环版本2):" << endl;
// 起始顶点入栈
stk.push(src_m);
while (!stk.empty())
{
size_t current = stk.top();
stk.pop();
// 如果当前顶点未被访问
if (!visited[current])
{
visited[current] = true;
cout << current << " : " << _vertexs[current] << endl;
// 将所有未访问的邻接点入栈
// 注意:为了保持与递归版本相同的访问顺序,需要逆序入栈
for (int i = n – 1; i >= 0; –i)
{
if (_matrix[current][i] != MAX_W && !visited[i])
{
stk.push(i);
}
}
}
}
cout << endl;
}
}
// 邻接表图的循环DFS实现
namespace ALGraph
{
template<class V, class W, bool direction>
void Graph<V, W, direction>::DFSIterative(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
stack<size_t> stk;
cout << "从顶点 " << src << " 开始的深度优先遍历(循环版本):" << endl;
// 将起始顶点入栈并标记访问
stk.push(src_m);
visited[src_m] = true;
cout << src_m << " : " << _vertexs[src_m] << endl;
while (!stk.empty())
{
size_t current = stk.top();
bool hasUnvisitedNeighbor = false;
// 遍历当前顶点的邻接表
GraphEdge* cur = _tables[current];
while (cur)
{
if (!visited[cur->_dst])
{
// 找到未访问的邻接点,访问并入栈
stk.push(cur->_dst);
visited[cur->_dst] = true;
cout << cur->_dst << " : " << _vertexs[cur->_dst] << endl;
hasUnvisitedNeighbor = true;
break; // 深度优先,先深入一个分支
}
cur = cur->_next;
}
// 如果没有未访问的邻接点,回溯
if (!hasUnvisitedNeighbor)
{
stk.pop();
}
}
cout << endl;
}
// 另一种实现方式:在弹出时访问
template<class V, class W, bool direction>
void Graph<V, W, direction>::DFSIterative2(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
stack<size_t> stk;
cout << "从顶点 " << src << " 开始的深度优先遍历(循环版本2):" << endl;
// 起始顶点入栈
stk.push(src_m);
while (!stk.empty())
{
size_t current = stk.top();
stk.pop();
// 如果当前顶点未被访问
if (!visited[current])
{
visited[current] = true;
cout << current << " : " << _vertexs[current] << endl;
// 为了保持与递归版本相同的访问顺序,需要将邻接点逆序入栈
// 先将邻接点收集到vector中
vector<size_t> neighbors;
GraphEdge* cur = _tables[current];
while (cur)
{
if (!visited[cur->_dst])
{
neighbors.push_back(cur->_dst);
}
cur = cur->_next;
}
// 逆序入栈
for (int i = neighbors.size() – 1; i >= 0; –i)
{
stk.push(neighbors[i]);
}
}
}
cout << endl;
}
}
测试代码为:
//邻接矩阵的深度遍历
void test3()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
AMGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.DFS("歌者");
cout << endl;
g1.DFS("观察者");
cout << endl;
g1.DFS("理想者");
cout << endl;
g1.DFS("幻想者");
cout << endl;
}
//邻接表的深度遍历
void test5()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
ALGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.DFS("歌者");
cout << endl;
g1.DFS("观察者");
cout << endl;
g1.DFS("理想者");
cout << endl;
g1.DFS("幻想者");
cout << endl;
}
测试结果为:


最小生成树
生成树对应于连通图。连通图中才能找到生成树
连通图中的每一棵生成树,都是原图的一个极大无环子图,即:从其中删去任何一条边,生成树就不在连通;反之,在其中引入任何一条新边,都会形成一条回路。
最小生成树的定义为构成该生成树的这些边的权值之和最小。 若连通图由n个顶点组成,则其生成树必含n个顶点和n-1条边。因此构造最小生成树的准则有三条:
只能使用图中的边来构造最小生成树
只能使用恰好n-1条边来连接图中的n个顶点
选用的n-1条边不能构成回路
构造最小生成树的方法:Kruskal算法和Prim算法。这两个算法都采用了逐步求解的贪心策略。 贪心算法:是指在问题求解时,总是做出当前看起来最好的选择。也就是说贪心算法做出的不是整体最优的的选择,而是某种意义上的局部最优解。贪心算法不是对所有的问题都能得到整体最优解
这个时候我们要用到并查集数据结构来判断两个结点间添加边是否成环
Kruskal算法
任给一个有n个顶点的连通网络N={V,E}, 首先构造一个由这n个顶点组成、不含任何边的图G={V,NULL},其中每个顶点自成一个连通分量, 其次不断从E中取出权值最小的一条边(若有多条任取其一),若该边的两个顶点来自不同的连通分量,则将此边加入到G中。如此重复,直到所有顶点在同一个连通分量上为止。 核心:每次迭代时,选出一条具有最小权值,且两端点不在同一连通分量上的边,加入生成树。
在《算法导论》中,关于Kruskal算法的介绍是这样的

实现如下:
UnionFindSet3.h
#pragma once
#include <vector>
using namespace std;
class UnionFindSet
{
public:
// 构造函数:初始时,将数组中元素全部设置为-1
UnionFindSet(size_t size) : _ufs(size, -1) {}
// 给一个元素的编号,找到该元素所在集合的根节点
int FindRoot(int index)
{
// 路径压缩优化:递归实现
if (_ufs[index] < 0) {
return index;
}
return _ufs[index] = FindRoot(_ufs[index]);
}
// 合并两个元素所在的集合
bool Union(int x1, int x2)
{
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
// x1已经与x2在同一个集合
if (root1 == root2) {
return false;
}
// 按秩合并(小树合并到大树):这里使用负数表示树的大小
if (_ufs[root1] > _ufs[root2]) { // root2的树更大(因为值更负)
_ufs[root2] += _ufs[root1];
_ufs[root1] = root2;
}
else {
_ufs[root1] += _ufs[root2];
_ufs[root2] = root1;
}
return true;
}
// 判断两个元素是否属于同一个集合
bool InSet(int x1, int x2)
{
return FindRoot(x1) == FindRoot(x2);
}
// 返回集合的数量(数组中负数的个数)
size_t Count() const
{
size_t count = 0;
for (auto e : _ufs) {
if (e < 0) {
++count;
}
}
return count;
}
// 获取指定集合的大小(绝对值的负数个数)
int GetSetSize(int index)
{
int root = FindRoot(index);
return -_ufs[root];
}
private:
vector<int> _ufs; // 负数表示根节点,其绝对值表示集合大小;正数表示父节点索引
};
Graph.h
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
using self = Graph<V, W, MAX_W, direction>;
//添加边
//两个顶点一个权值
//辅助子函数
void _AddEdge(size_t src_m, size_t dst_m, const W& w)
{
_matrix[src_m][dst_m] = w;
//无向图
if (direction == false)
{
_matrix[src_m][dst_m] = w;
}
}
//主函数
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
_AddEdge(src_m, dst_m,w);
}
struct Edge
{
size_t _src;//源点的下标
size_t _dst;//目标点的下标
W _w;//权值
Edge(size_t srci, size_t dsti, const W& w)
:_src(srci), _dst(dsti), _w(w)
{
}
bool operator>(const Edge& e) const
{
return _w > e._w;
}
};
//Kruskal最小生成树
W Kruskal(self& mintree)
{
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
priority_queue<Edge,vector<Edge>,greater<Edge>>minpq;
for (size_t i =0;i<n;++i)
{
for (size_t j = 0; j < n; ++j)
{
if (i<j&&_matrix[i][j] != MAX_W)
{
minpq.push(Edge(i,j, _matrix[i][j]));
}
}
}
//选n-1条边
size_t size = 0;
W totalW = W();
UnionFindSet ufs(n);
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
if (!ufs.InSet(min._src,min._dst))
{
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
mintree._AddEdge(min._src,min._dst,min._w);
ufs.Union(min._src, min._dst);
++size;
totalW += min._w;
}
else
{
cout << "构成环:/t";
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
测试代码:
#define _CRT_SECURE_NO_WARNINGS
#include"Graph.h"
#include"UnionFindSet.h"
void testMintree()
{
const char* str = "abcdefghi";
AMGraph::Graph<char, int> g(str, strlen(str));
g.AddEdge('a', 'b', 4);
g.AddEdge('a', 'h', 8);
g.AddEdge('a', 'h', 9);
g.AddEdge('b', 'c', 8);
g.AddEdge('b', 'h', 11);
g.AddEdge('c', 'i', 2);
g.AddEdge('c', 'f', 4);
g.AddEdge('c', 'd', 7);
g.AddEdge('d', 'f', 14);
g.AddEdge('d', 'e', 9);
g.AddEdge('e', 'f', 10);
g.AddEdge('f', 'g', 2);
g.AddEdge('g', 'h', 1);
g.AddEdge('g', 'i', 6);
g.AddEdge('h', 'i', 7);
AMGraph::Graph<char, int> kminTree;
cout << "Kruskal:" << g.Kruskal(kminTree) << endl;
}
int main()
{
testMintree()
return 0;
}
结果为:

Prim算法
Prim算法是对 Kruskal算法的一个特例情况
在《算法导论》中,关于Kruskal算法的介绍是这样的

实现如下:
set实现版本
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
using self = Graph<V, W, MAX_W, direction>;
//添加边
//两个顶点一个权值
//辅助子函数
void _AddEdge(size_t src_m, size_t dst_m, const W& w)
{
_matrix[src_m][dst_m] = w;
//无向图
if (direction == false)
{
_matrix[src_m][dst_m] = w;
}
}
//主函数
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
_AddEdge(src_m, dst_m,w);
}
struct Edge
{
size_t _src;//源点的下标
size_t _dst;//目标点的下标
W _w;//权值
Edge(size_t srci, size_t dsti, const W& w)
:_src(srci), _dst(dsti), _w(w)
{
}
bool operator>(const Edge& e) const
{
return _w > e._w;
}
};
//Prim最小生成树
//set实现版本
W Prim_Set(self& mintree,const V&src)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
set<int>X;
set<int>Y;
X.insert(srci);
for (size_t i = 0; i < n; ++i)
{
if (i != srci)
{
Y.insert(i);
}
}
//从X到Y集合中选出权值最小的边
priority_queue<Edge, vector<Edge>, greater<Edge>> minpq;
//将srci的边添加到队列中
for (size_t i=0;i<n;++i)
{
if (_matrix[srci][i] != MAX_W)
{
minpq.push(Edge(srci, i, _matrix[srci][i]));
}
}
size_t size = 0;
W totalW = W();
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
mintree._AddEdge(min._src,min._dst,min._w);
X.insert(min._dst);
Y.erase(min._dst);
++size;
totalW += min._w;
if (size == n – 1)
{
break;
}
for (size_t i = 0; i < n; ++i)
{
if (_matrix[min._dst][i] != MAX_W&&X.count(i)==0)
{
minpq.push(Edge(min._dst, i, _matrix[min._dst][i]));
}
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
vector实现版本
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
using self = Graph<V, W, MAX_W, direction>;
//添加边
//两个顶点一个权值
//辅助子函数
void _AddEdge(size_t src_m, size_t dst_m, const W& w)
{
_matrix[src_m][dst_m] = w;
//无向图
if (direction == false)
{
_matrix[src_m][dst_m] = w;
}
}
//主函数
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
_AddEdge(src_m, dst_m,w);
}
struct Edge
{
size_t _src;//源点的下标
size_t _dst;//目标点的下标
W _w;//权值
Edge(size_t srci, size_t dsti, const W& w)
:_src(srci), _dst(dsti), _w(w)
{
}
bool operator>(const Edge& e) const
{
return _w > e._w;
}
};
//Prim最小生成树
//vector版本
W Prim_Vector(self& mintree, const V& src)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
vector<bool>X(n,false);
vector<bool>Y(n, true);
X[srci] = true;
Y[srci] = false;
//从X到Y集合中选出权值最小的边
priority_queue<Edge, vector<Edge>, greater<Edge>> minpq;
//将srci的边添加到队列中
for (size_t i = 0; i < n; ++i)
{
if (_matrix[srci][i] != MAX_W)
{
minpq.push(Edge(srci, i, _matrix[srci][i]));
}
}
size_t size = 0;
W totalW = W();
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
//如果最小边的点也在X集合,则构成环
if (X[min._dst])
{
cout << "构成环:/t";
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
}
else
{
mintree._AddEdge(min._src, min._dst, min._w);
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
X[min._src] = true;
Y[min._dst] = false;
++size;
totalW += min._w;
if (size == n – 1)
{
break;
}
for (size_t i = 0; i < n; ++i)
{
if (_matrix[min._dst][i] != MAX_W && Y[i])
//或者if (_matrix[min._dst][i] != MAX_W && X[i]==0)
{
minpq.push(Edge(min._dst, i, _matrix[min._dst][i]));
}
}
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
测试代码:
#define _CRT_SECURE_NO_WARNINGS
#include"Graph.h"
#include"UnionFindSet.h"
void testMintree()
{
const char* str = "abcdefghi";
AMGraph::Graph<char, int> g(str, strlen(str));
g.AddEdge('a', 'b', 4);
g.AddEdge('a', 'h', 8);
g.AddEdge('a', 'h', 9);
g.AddEdge('b', 'c', 8);
g.AddEdge('b', 'h', 11);
g.AddEdge('c', 'i', 2);
g.AddEdge('c', 'f', 4);
g.AddEdge('c', 'd', 7);
g.AddEdge('d', 'f', 14);
g.AddEdge('d', 'e', 9);
g.AddEdge('e', 'f', 10);
g.AddEdge('f', 'g', 2);
g.AddEdge('g', 'h', 1);
g.AddEdge('g', 'i', 6);
g.AddEdge('h', 'i', 7);
AMGraph::Graph<char, int> pminTree;
cout << "Prim:" << g.Prim(pminTree, 'a') << endl;
pminTree.Print();
}
int main()
{
testMintree()
return 0;
}
结果为:

最短路径问题
最短路径问题:从在带权有向图G中的某一顶点出发,找出一条通往另一顶点的最短路径,最短也就是沿路径各边的权值总和达到最小。
单源最短路径–Dijkstra算法
单源最短路径问题:给定一个图G = ( V , E ) G=(V,E)G=(V,E),求源结点s ∈ V s∈Vs∈V到图中每个结点v ∈ V v∈Vv∈V的最短路径。
Dijkstra算法就适用于解决带权重的有向图上的单源最短路径问题,同时算法要求图中所有边的权重非负。一般在求解最短路径的时候都是已知一个起点和一个终点,所以使用Dijkstra算法求解过后也就得到了所需起点到终点的最短路径。
针对一个带权有向图G,将所有结点分为两组S和Q,S是已经确定最短路径的结点集合,在初始时为空(初始时就可以将源节点s放入,毕竟源节点到自己的代价是0),Q 为其余未确定最短路径的结点集合,每次从Q 中找出一个起点到该结点代价最小的结点u ,将u 从Q 中移出,并放入S中,对u 的每一个相邻结点v 进行松弛操作。
松弛即对每一个相邻结点v ,判断源节点s到结点u的代价与u 到v 的代价之和是否比原来s 到v 的代价更小,若代价比原来小则要将s 到v 的代价更新为s 到u 与u 到v 的代价之和,否则维持原样。
如此一直循环直至集合Q 为空,即所有节点都已经查找过一遍并确定了最短路径,至于一些起点到达不了的结点在算法循环后其代价仍为初始设定的值,不发生变化。Dijkstra算法每次都是选择V-S中最小的路径节点来进行更新,并加入S中,所以该算法使用的是贪心策略。
Dijkstra算法存在的问题是不支持图中带负权路径,如果带有负权路径,则可能会找不到一些路径的最短路径。
《算法导论》中关于Dijkstra算法的介绍和图示是这样的:
实现图示

实现如下
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
//单源最短路径算法——Dijkstra算法
//时间复杂度O(N^2)空间复杂度O(N)
void Dijkstra(const V&src ,vector<W>&dict,vector<int>&Ppath)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
dict.resize(n,MAX_W);
Ppath.resize(n,-1);
dict[srci] = W();
Ppath[srci] = srci;
//已经确定最短路径的集合
vector<bool>S(n,false);
S[srci] = true;
for (size_t j = 0; j < n; ++j)
{
//选最短路径顶点且不在S处更新其他路径
int u = srci;
W min = MAX_W;
for (size_t i = 0; i < n; ++i)
{
if (S[i] == false && dict[i] < min)
{
u = i;
min = dict[i];
}
}
S[u] = true;
//松弛更新u链接顶点V
//srci->u, u->v小于srci->v就更新
for (size_t v = 0; v < n; ++v)
{
if (S[v]==false && _matrix[u][v] != MAX_W &&
dict[u] + _matrix[u][v] < dict[v])
{
dict[v] = dict[u] + _matrix[u][v];
Ppath[v] = u;
}
}
}
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
测试函数:
// 打印最短路径的逻辑算法
void PrinrtShotPath(const V& src, const vector<W>& dist, const vector<int>& parentPath)
{
size_t N = _vertexs.size();
size_t srci = GetVertexsIndex(src);
for (size_t i = 0; i < N; ++i)
{
if (i == srci)
continue;
vector<int> path;
int parenti = i;
while (parenti != srci)
{
path.push_back(parenti);
parenti = parentPath[parenti];
}
path.push_back(srci);
reverse(path.begin(), path.end());
for (auto pos : path)
{
cout << _vertexs[pos] << "->";
}
cout << dist[i] << endl;
}
}
测试代码:
void TestGraphDijkstra()
{
const char* str1 = "syztx";
AMGraph::Graph<char, int, INT_MAX, true> g1(str1, strlen(str1));
g1.AddEdge('s', 't', 10);
g1.AddEdge('s', 'y', 5);
g1.AddEdge('y', 't', 3);
g1.AddEdge('y', 'x', 9);
g1.AddEdge('y', 'z', 2);
g1.AddEdge('z', 's', 7);
g1.AddEdge('z', 'x', 6);
g1.AddEdge('t', 'y', 2);
g1.AddEdge('t', 'x', 1);
g1.AddEdge('x', 'z', 4);
vector<int> dist1;
vector<int> parentPath1;
g1.Dijkstra('s', dist1, parentPath1);
g1.PrinrtShotPath('s', dist1, parentPath1);
// 图中带有负权路径时,贪心策略则失效了。
// 测试结果可以看到s->t->y之间的最短路径没更新出来
const char* str2 = "sytx";
AMGraph::Graph<char, int, INT_MAX, true> g2(str2, strlen(str2));
g2.AddEdge('s', 't', 10);
g2.AddEdge('s', 'y', 5);
g2.AddEdge('t', 'y', -7);
g2.AddEdge('y', 'x', 3);
vector<int> dist2;
vector<int> parentPath2;
g2.Dijkstra('s', dist2, parentPath2);
g2.PrinrtShotPath('s', dist2, parentPath2);
}
结果为:

单源最短路径–Bellman-Ford算法
Dijkstra算法只能用来解决正权图的单源最短路径问题,但有些情况下会出现负权图。这时这个算法就不能帮助我们解决问题了,而Bellman-Ford算法可以解决负权图的单源最短路径问题。
它的优点是可以解决有负权边的单源最短路径问题,而且可以用来判断是否有负权回路。
它的缺点,它的时间复杂度 O(N*E) (N是点数,E是边数)普遍是要高于Dijkstra算法O(N²)的。
如果我们使用邻接矩阵实现,那么遍历所有边的数量的时间复杂度就是O(N^3),这里也可以看出来Bellman-Ford就是一种暴力求解更新
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
//单源最短路径算法——Bellman-Ford算法
//时间复杂度O(N^3)空间复杂度O(N)
bool BellmanFord(const V& src, vector<W>& dict, vector<int>& Ppath)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
dict.resize(n, MAX_W);
Ppath.resize(n, -1);
//先更新srci->srci
dict[srci] = W();
for (size_t k = 0; k < n – 1; ++k)
{
//i->j更新次数
for (size_t i = 0; i < n; ++i)
{
bool updated = false;
//srci->i->j
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W && dict[i] + _matrix[i][j] < dict[j])
{
dict[j] = dict[i] + _matrix[i][j];
Ppath[j] = i;
updated = true;
}
}
if (updated == false)
break;
}
}
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W && dict[i] + _matrix[i][j] < dict[j])
{
return false;//存在负权回路
}
}
}
return true;
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
测试函数:
// 打印最短路径的逻辑算法
void PrinrtShotPath(const V& src, const vector<W>& dist, const vector<int>& parentPath)
{
size_t N = _vertexs.size();
size_t srci = GetVertexsIndex(src);
for (size_t i = 0; i < N; ++i)
{
if (i == srci)
continue;
vector<int> path;
int parenti = i;
while (parenti != srci)
{
path.push_back(parenti);
parenti = parentPath[parenti];
}
path.push_back(srci);
reverse(path.begin(), path.end());
for (auto pos : path)
{
cout << _vertexs[pos] << "->";
}
cout << dist[i] << endl;
}
}
测试代码:
void TestGraphBellmanFord()
{
const char* str = "syztx";
AMGraph::Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 6);
g.AddEdge('s', 'y', 7);
g.AddEdge('y', 'z', 9);
g.AddEdge('y', 'x', -3);
g.AddEdge('z', 's', 2);
g.AddEdge('z', 'x', 7);
g.AddEdge('t', 'x', 5);
g.AddEdge('t', 'y', 8);
g.AddEdge('t', 'z', -4);
// 5.3 多源最短路径–Floyd-Warshall算法
// Floyd-Warshall算法是解决任意两点间的最短路径的一种算法。
// Floyd算法考虑的是一条最短路径的中间节点,即简单路径p={v1,v2,…,vn}上除v1和vn的任意节点。
// 设k是p的一个中间节点,那么从i到j的最短路径p就被分成i到k和k到j的两段最短路径p1,p2。
// p1是从i到k且中间节点属于{1,2,…,k-1}取得的一条最短路径。
// p2是从k到j且中间节点属于{1,2,…,k-1}取得的一条最短路径。
g.AddEdge('x', 't', -2);
vector<int> dist;
vector<int> parentPath;
if (g.BellmanFord('s', dist, parentPath))
{
g.PrinrtShotPath('s', dist, parentPath);
}
else
{
cout << "存在负权回路" << endl;
}
// 微调图结构,带有负权回路的测试
/*
const char* str = "syztx";
Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 6);
g.AddEdge('s', 'y', 7);
g.AddEdge('y', 'x', -3);
g.AddEdge('y', 'z', 9);
g.AddEdge('y', 'x', -3);
g.AddEdge('y', 's', 1); // 新增
g.AddEdge('z', 's', 2);
g.AddEdge('z', 'x', 7);
g.AddEdge('t', 'x', 5);
g.AddEdge('t', 'y', -8); // 更改
g.AddEdge('t', 'z', -4);
g.AddEdge('x', 't', -2);
vector<int> dist;
vector<int> parentPath;
if (g.BellmanFord('s', dist, parentPath))
{
g.PrinrtShotPath('s', dist, parentPath);
}
else
{
cout << "存在负权回路" << endl;
}
*/
}
多源最短路径–Floyd-Warshall算法
Floyd-Warshall算法是解决任意两点间的最短路径的一种算法。
Floyd算法考虑的是一条最短路径的中间节点,即简单路径p={v1,v2,…,vn}上除v1和vn的任意节点。
设k是p的一个中间节点,那么从i到j的最短路径p就被分成i到k和k到j的两段最短路径p1,p2。p1是从i到k且中间节点属于{1,2,…,k-1}取得的一条最短路径。p2是从k到j且中间节点属于{1, 2,…,k-1}取得的一条最短路径。
《算法导论》中对其的描述是这样的:

Floyd-Warshall算法的原理是动态规划。
设 Di,j,kDi,j,k 为从 ii 到 jj 的只以 (1..k)(1..k) 集合中的节点为中间节点的最短路径的长度。
若最短路径经过点 kk,则
Di,j,k=Di,k,k−1+Dk,j,k−1;Di,j,k=Di,k,k−1+Dk,j,k−1;
若最短路径不经过点 kk,则
Di,j,k=Di,j,k−1.Di,j,k=Di,j,k−1.
因此,
Di,j,k=min(Di,j,k−1,Di,k,k−1+Dk,j,k−1).Di,j,k=min(Di,j,k−1,Di,k,k−1+Dk,j,k−1).
即Floyd算法本质是三维动态规划,D[i][j][k]表示从点i到点j只经过0到k个点最短路径,然后建立起转移方程,然后通过空间优化,优化掉最后一维度,变成一个最短路径的迭代算法,最后即得到所以点的最短路。
代码实现:
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<iomanip>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
//多源最短路径算法——Floyd-Warshall算法
void FloydWarShall(vector<vector<W>>& dict, vector<vector<int>>& Ppath)
{
size_t n = _vertexs.size();
dict.resize(n);
Ppath.resize(n);
// 初始化权值和路径矩阵
for (size_t i = 0; i < n; ++i)
{
dict[i].resize(n, MAX_W);
Ppath[i].resize(n, -1);
}
// 将直接相连的路径初始化
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W)
{
dict[i][j] = _matrix[i][j];
Ppath[i][j] = i;
}
else
{
Ppath[i][j] = -1;
}
if (i == j)
{
dict[i][j] = W();
}
}
}
// 依次用顶点k作为中转点更新最短路径
for (size_t k = 0; k < n; ++k)
{
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
// i->k + k->j 比 i->j前面更新的距离更短,则更新
if (dict[i][k] != MAX_W && dict[k][j] != MAX_W
&& dict[i][k] + dict[k][j] < dict[i][j])
{
// 找跟j相连的上一个邻接顶点
// 如果k->j 直接相连,上一个点就k,vvpPath[k][j]存就是k
// 如果k->j 没有直接相连,k->…->x->j,vvpPath[k][j]存就是x
dict[i][j] = dict[i][k] + dict[k][j];
Ppath[i][j] = Ppath[k][j];
}
}
}
}
// 打印权值和路径矩阵观察数据
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (dict[i][j] == MAX_W)
{
//cout << "*" << " ";
printf("%3c", '*');
}
else
{
//cout << dict[i][j] << " ";
printf("%3d", dict[i][j]);
}
}
cout << endl;
}
cout << endl;
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
//cout << Ppath[i][j] << " ";
printf("%3d", Ppath[i][j]);
}
cout << endl;
}
cout << "=================================" << endl;
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
测试代码:
void TestFloydWarShall()
{
const char* str = "12345";
AMGraph::Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('1', '2', 3);
g.AddEdge('1', '3', 8);
g.AddEdge('1', '5', -4);
g.AddEdge('2', '4', 1);
g.AddEdge('2', '5', 7);
g.AddEdge('3', '2', 4);
g.AddEdge('4', '1', 2);
g.AddEdge('4', '3', -5);
g.AddEdge('5', '4', 6);
vector<vector<int>> vvDist;
vector<vector<int>> vvParentPath;
g.FloydWarShall(vvDist, vvParentPath);
// 打印任意两点之间的最短路径
for (size_t i = 0; i < strlen(str); ++i)
{
g.PrinrtShotPath(str[i], vvDist[i], vvParentPath[i]);
cout << endl;
}
}
测试结果为:

源码
Graph.h
#pragma once
#include"UnionFindSet3.h"
#include<vector>
#include<cstdio>
#include<stdexcept>
#include<set>
#include<iostream>
#include<map>
#include<queue>
#include<tuple>
#include<string>
using namespace std;
//邻接矩阵图
namespace AMGraph
{//顶点 权值 权值的最大值 是否有向
template<class V, class W, W MAX_W = INT_MAX, bool direction = false>
//权值很多时候是整型
class Graph
{
using self = Graph<V, W, MAX_W, direction>;
public:
//图的创建
//1、IO输入(不便于测试)
//2、写入文件读取文件(不便于改)
//3、手动添加边
Graph() = default;
//顶点数组构造
Graph(const V* a, size_t n)
//n为顶点
{
_vertexs.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_vertexs.push_back(a[i]);
_IndexMap[a[i]] = i;
}
_matrix.resize(n);
for (size_t i = 0; i < _matrix.size(); ++i)
{
_matrix[i].resize(n, MAX_W);
}
}
// 构造函数2:初始化列表构造函数 – 从顶点列表和边列表构造
Graph(std::initializer_list<V> vertices, std::initializer_list<std::tuple<V, V, W>> edges)
{
// 初始化顶点
size_t n = vertices.size();
_vertexs.reserve(n);
size_t idx = 0;
for (const auto& vertex : vertices)
{
_vertexs.push_back(vertex);
_IndexMap[vertex] = idx++;
}
// 初始化邻接矩阵
_matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
_matrix[i].resize(n, MAX_W);
}
// 添加边
for (const auto& edge : edges)
{
V src, dst;
W weight;
std::tie(src, dst, weight) = edge; // 解包元组
AddEdge(src, dst, weight);
}
}
//从顶点向量和边向量构造
Graph(const std::vector<V>& vertices, const std::vector<std::tuple<V, V, W>>& edges)
{
// 初始化顶点
size_t n = vertices.size();
_vertexs.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_vertexs.push_back(vertices[i]);
_IndexMap[vertices[i]] = i;
}
// 初始化邻接矩阵
_matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
_matrix[i].resize(n, MAX_W);
}
// 添加边
for (const auto& edge : edges)
{
V src, dst;
W weight;
std::tie(src, dst, weight) = edge;
AddEdge(src, dst, weight);
}
}
//从顶点和边的初始化列表(简化版本)
Graph(std::initializer_list<std::pair<V, std::vector<std::pair<V, W>>>> adjList)
{
// 第一步:添加所有顶点
for (const auto& vertex_edges : adjList)
{
AddVertex(vertex_edges.first);
}
// 第二步:添加所有边
for (const auto& vertex_edges : adjList)
{
V src = vertex_edges.first;
for (const auto& edge : vertex_edges.second)
{
AddEdge(src, edge.first, edge.second);
}
}
}
// 从邻接矩阵直接构造
Graph(const std::vector<V>& vertices, const std::vector<std::vector<W>>& matrix)
: _vertexs(vertices), _matrix(matrix)
{
if (vertices.size() != matrix.size())
throw std::invalid_argument("顶点数与邻接矩阵维度不匹配");
for (size_t i = 0; i < vertices.size(); ++i)
{
_IndexMap[vertices[i]] = i;
}
}
// 添加顶点
size_t AddVertex(const V& vertex)
{
auto it = _IndexMap.find(vertex);
if (it != _IndexMap.end())
{
return it->second; // 顶点已存在,返回其下标
}
size_t index = _vertexs.size();
_vertexs.push_back(vertex);
_IndexMap[vertex] = index;
// 扩展邻接矩阵
for (auto& row : _matrix)
{
row.push_back(MAX_W);
}
_matrix.push_back(std::vector<W>(index + 1, MAX_W));
return index;
}
//确定顶点的下标
size_t GetVertexsIndex(const V& v)
{
auto it = _IndexMap.find(v);
if (it != _IndexMap.end())
{
return it->second;
}
else
{
//assert(false);
cout << "顶点:" << v << "不存在" << endl;
throw std::invalid_argument("定点不存在");
return -1;
}
}
//添加边
//两个顶点一个权值
//辅助子函数
void _AddEdge(size_t src_m, size_t dst_m, const W& w)
{
_matrix[src_m][dst_m] = w;
//无向图
if (direction == false)
{
_matrix[src_m][dst_m] = w;
}
}
//主函数
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
_AddEdge(src_m, dst_m,w);
}
//广度优先遍历
void BFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
queue<int>q;
q.push(src_m);
size_t n = _vertexs.size();
vector<bool>visited(n, false);
int levelsize = 1;
visited[src_m] = true;
cout << "从顶点 " << src << " 开始的广度优先遍历:" << endl;
while (!q.empty())
{
//一层一层出
for (size_t i = 0; i < levelsize; ++i)
{
int front = q.front();
q.pop();
cout << front << " : " << _vertexs[front] << endl;
//把邻接顶点入队列
for (size_t i = 0; i < n; ++i)
{
if (_matrix[front][i] != MAX_W)
{
if (visited[i] == false)
{
q.push(i);
visited[i] = true;
}
}
}
}
printf("\\n");
levelsize = q.size();
}
printf("\\n");
}
//深度优先遍历
void DFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool>visited(n, false);
cout << "从顶点 " << src << " 开始的深度优先遍历:" << endl;
_DFS(src_m, visited);
cout << endl;
}
//深度优先子函数
void _DFS(size_t src_m, vector<bool>& visited)
{
cout << src_m << " : " << _vertexs[src_m] << endl;
visited[src_m] = true;
//找src_m相邻的点去深度访问
for (size_t i = 0; i < _vertexs.size(); ++i)
{
if (_matrix[src_m][i] != MAX_W && visited[i] == false)
{
_DFS(i, visited);
}
}
}
void Print()
{
// 顶点与下标的映射
//横下表
for (size_t i = 0; i < _vertexs.size(); ++i)
{
cout << "[" << i << "]" << "->" << _vertexs[i] << endl;
}
cout << endl;
//矩阵
//横坐标
cout << " ";
for (size_t i = 0; i < _vertexs.size(); ++i)
{
//cout << i << " ";
printf("%4d", i);
}
cout << endl;
for (size_t i = 0; i < _matrix.size(); ++i)
{
//纵坐标
cout << i << " ";
//矩阵
for (size_t j = 0; j < _matrix[i].size(); ++j)
{
if (_matrix[i][j] == MAX_W)
{
//cout << "* ";
printf("%4c", '*');
}
else
{
//cout << _matrix[i][j] << " ";
printf("%4d", i);
}
}
cout << endl;
}
cout << endl;
}
struct Edge
{
size_t _src;//源点的下标
size_t _dst;//目标点的下标
W _w;//权值
Edge(size_t srci, size_t dsti, const W& w)
:_src(srci), _dst(dsti), _w(w)
{
}
bool operator>(const Edge& e) const
{
return _w > e._w;
}
};
//Kruskal最小生成树
W Kruskal(self& mintree)
{
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
priority_queue<Edge,vector<Edge>,greater<Edge>>minpq;
for (size_t i =0;i<n;++i)
{
for (size_t j = 0; j < n; ++j)
{
if (i<j&&_matrix[i][j] != MAX_W)
{
minpq.push(Edge(i,j, _matrix[i][j]));
}
}
}
//选n-1条边
size_t size = 0;
W totalW = W();
UnionFindSet ufs(n);
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
if (!ufs.InSet(min._src,min._dst))
{
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
mintree._AddEdge(min._src,min._dst,min._w);
ufs.Union(min._src, min._dst);
++size;
totalW += min._w;
}
else
{
cout << "构成环:/t";
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
//Prim最小生成树
//set实现版本
W Prim_Set(self& mintree,const V&src)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
set<int>X;
set<int>Y;
X.insert(srci);
for (size_t i = 0; i < n; ++i)
{
if (i != srci)
{
Y.insert(i);
}
}
//从X到Y集合中选出权值最小的边
priority_queue<Edge, vector<Edge>, greater<Edge>> minpq;
//将srci的边添加到队列中
for (size_t i=0;i<n;++i)
{
if (_matrix[srci][i] != MAX_W)
{
minpq.push(Edge(srci, i, _matrix[srci][i]));
}
}
size_t size = 0;
W totalW = W();
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
mintree._AddEdge(min._src,min._dst,min._w);
X.insert(min._dst);
Y.erase(min._dst);
++size;
totalW += min._w;
if (size == n – 1)
{
break;
}
for (size_t i = 0; i < n; ++i)
{
if (_matrix[min._dst][i] != MAX_W&&X.count(i)==0)
{
minpq.push(Edge(min._dst, i, _matrix[min._dst][i]));
}
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
//vector版本
W Prim_Vector(self& mintree, const V& src)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
mintree._vertexs = _vertexs;
mintree._IndexMap = _IndexMap;
mintree._matrix.resize(n);
for (size_t i = 0; i < n; ++i)
{
mintree._matrix[i].resize(n);
}
vector<bool>X(n,false);
vector<bool>Y(n, true);
X[srci] = true;
Y[srci] = false;
//从X到Y集合中选出权值最小的边
priority_queue<Edge, vector<Edge>, greater<Edge>> minpq;
//将srci的边添加到队列中
for (size_t i = 0; i < n; ++i)
{
if (_matrix[srci][i] != MAX_W)
{
minpq.push(Edge(srci, i, _matrix[srci][i]));
}
}
size_t size = 0;
W totalW = W();
while (!minpq.empty())
{
Edge min = minpq.top();
minpq.pop();
//如果最小边的点也在X集合,则构成环
if (X[min._dst])
{
cout << "构成环:/t";
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
}
else
{
mintree._AddEdge(min._src, min._dst, min._w);
cout << _vertexs[min._src] << "-" << _vertexs[min._dst] << "-" << min._w << endl;
X[min._src] = true;
Y[min._dst] = false;
++size;
totalW += min._w;
if (size == n – 1)
{
break;
}
for (size_t i = 0; i < n; ++i)
{
if (_matrix[min._dst][i] != MAX_W && Y[i])
//或者if (_matrix[min._dst][i] != MAX_W && X[i]==0)
{
minpq.push(Edge(min._dst, i, _matrix[min._dst][i]));
}
}
}
}
if (size == n – 1)
{
return totalW;
}
else
{
return W();
}
}
//单源最短路径算法——Dijkstra算法
//时间复杂度O(N^2)空间复杂度O(N)
void Dijkstra(const V&src ,vector<W>&dict,vector<int>&Ppath)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
dict.resize(n,MAX_W);
Ppath.resize(n,-1);
dict[srci] = W();
Ppath[srci] = srci;
//已经确定最短路径的集合
vector<bool>S(n,false);
S[srci] = true;
for (size_t j = 0; j < n; ++j)
{
//选最短路径顶点且不在S处更新其他路径
int u = srci;
W min = MAX_W;
for (size_t i = 0; i < n; ++i)
{
if (S[i] == false && dict[i] < min)
{
u = i;
min = dict[i];
}
}
S[u] = true;
//松弛更新u链接顶点V
//srci->u, u->v小于srci->v就更新
for (size_t v = 0; v < n; ++v)
{
if (S[v]==false && _matrix[u][v] != MAX_W &&
dict[u] + _matrix[u][v] < dict[v])
{
dict[v] = dict[u] + _matrix[u][v];
Ppath[v] = u;
}
}
}
}
//单源最短路径算法——Bellman-Ford算法
//时间复杂度O(N^3)空间复杂度O(N)
bool BellmanFord(const V& src, vector<W>& dict, vector<int>& Ppath)
{
size_t srci = GetVertexsIndex(src);
size_t n = _vertexs.size();
dict.resize(n, MAX_W);
Ppath.resize(n, -1);
//先更新srci->srci
dict[srci] = W();
for (size_t k = 0; k < n – 1; ++k)
{
//i->j更新次数
for (size_t i = 0; i < n; ++i)
{
bool updated = false;
//srci->i->j
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W && dict[i] + _matrix[i][j] < dict[j])
{
dict[j] = dict[i] + _matrix[i][j];
Ppath[j] = i;
updated = true;
}
}
if (updated == false)
break;
}
}
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W && dict[i] + _matrix[i][j] < dict[j])
{
return false;//存在负权回路
}
}
}
return true;
}
//多源最短路径算法——Floyd-Warshall算法
void FloydWarShall(vector<vector<W>>& dict, vector<vector<int>>& Ppath)
{
size_t n = _vertexs.size();
dict.resize(n);
Ppath.resize(n);
// 初始化权值和路径矩阵
for (size_t i = 0; i < n; ++i)
{
dict[i].resize(n, MAX_W);
Ppath[i].resize(n, -1);
}
// 将直接相连的路径初始化
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (_matrix[i][j] != MAX_W)
{
dict[i][j] = _matrix[i][j];
Ppath[i][j] = i;
}
else
{
Ppath[i][j] = -1;
}
if (i == j)
{
dict[i][j] = W();
}
}
}
// 依次用顶点k作为中转点更新最短路径
for (size_t k = 0; k < n; ++k)
{
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
// i->k + k->j 比 i->j前面更新的距离更短,则更新
if (dict[i][k] != MAX_W && dict[k][j] != MAX_W
&& dict[i][k] + dict[k][j] < dict[i][j])
{
// 找跟j相连的上一个邻接顶点
// 如果k->j 直接相连,上一个点就k,vvpPath[k][j]存就是k
// 如果k->j 没有直接相连,k->…->x->j,vvpPath[k][j]存就是x
dict[i][j] = dict[i][k] + dict[k][j];
Ppath[i][j] = Ppath[k][j];
}
}
}
}
// 打印权值和路径矩阵观察数据
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (dict[i][j] == MAX_W)
{
//cout << "*" << " ";
printf("%3c", '*');
}
else
{
//cout << dict[i][j] << " ";
printf("%3d", dict[i][j]);
}
}
cout << endl;
}
cout << endl;
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
//cout << Ppath[i][j] << " ";
printf("%3d", Ppath[i][j]);
}
cout << endl;
}
cout << "=================================" << endl;
}
// 打印最短路径的逻辑算法
void PrinrtShotPath(const V& src, const vector<W>& dist, const vector<int>& parentPath)
{
size_t N = _vertexs.size();
size_t srci = GetVertexsIndex(src);
for (size_t i = 0; i < N; ++i)
{
if (i == srci)
continue;
vector<int> path;
int parenti = i;
while (parenti != srci)
{
path.push_back(parenti);
parenti = parentPath[parenti];
}
path.push_back(srci);
reverse(path.begin(), path.end());
for (auto pos : path)
{
cout << _vertexs[pos] << "->";
}
cout << dist[i] << endl;
}
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<vector<W>> _matrix;//邻接矩阵
};
}
//邻接表图
namespace ALGraph
{
//边
template<class W>
struct Edge
{
size_t _src;//源点的下标
size_t _dst;//目标点的下标
const W _w;//权值
Edge<W>* _next;//链接下一个点的指针
Edge(const W& w)
: _src(-1)
, _dst(-1)
, _w(w)
, _next(nullptr)
{
}
};
//顶点 权值 是否有向
template<class V, class W, bool direction = false>
//权值很多时候是整型
class Graph
{
using GraphEdge = Edge<W>;
public:
//图的创建
//1、IO输入(不便于测试)
//2、写入文件读取文件(不便于改)
//3、手动添加边
//顶点数组构造
Graph(const V* a, size_t n)
//n为顶点
{
_vertexs.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_vertexs.push_back(a[i]);
_IndexMap[a[i]] = i;
}
_tables.resize(n, nullptr);
}
// 默认构造函数
Graph() = default;
// 列表初始化构造函数1: 只初始化顶点
Graph(std::initializer_list<V> vertices)
{
size_t n = vertices.size();
_vertexs.reserve(n);
size_t idx = 0;
for (const auto& vertex : vertices)
{
_vertexs.push_back(vertex);
_IndexMap[vertex] = idx++;
}
_tables.resize(n, nullptr);
}
// 列表初始化构造函数2: 使用顶点列表和边列表
Graph(std::initializer_list<V> vertices, std::initializer_list<std::tuple<V, V, W>> edges)
{
// 初始化顶点
size_t n = vertices.size();
_vertexs.reserve(n);
size_t idx = 0;
for (const auto& vertex : vertices)
{
_vertexs.push_back(vertex);
_IndexMap[vertex] = idx++;
}
_tables.resize(n, nullptr);
// 添加边
for (const auto& edge : edges)
{
V src, dst;
W weight;
std::tie(src, dst, weight) = edge;
AddEdge(src, dst, weight);
}
}
// 列表初始化构造函数3: 从向量构造
Graph(const std::vector<V>& vertices, const std::vector<std::tuple<V, V, W>>& edges)
{
// 初始化顶点
size_t n = vertices.size();
_vertexs.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_vertexs.push_back(vertices[i]);
_IndexMap[vertices[i]] = i;
}
_tables.resize(n, nullptr);
// 添加边
for (const auto& edge : edges)
{
V src, dst;
W weight;
std::tie(src, dst, weight) = edge;
AddEdge(src, dst, weight);
}
}
// 列表初始化构造函数4: 从邻接表格式初始化 (顶点->邻接顶点列表)
Graph(std::initializer_list<std::pair<V, std::initializer_list<std::pair<V, W>>>> adjList)
{
// 第一步:收集所有顶点
for (const auto& vertex_edges : adjList)
{
AddVertex(vertex_edges.first);
for (const auto& edge : vertex_edges.second)
{
AddVertex(edge.first);
}
}
// 第二步:添加边
for (const auto& vertex_edges : adjList)
{
V src = vertex_edges.first;
for (const auto& edge : vertex_edges.second)
{
AddEdge(src, edge.first, edge.second);
}
}
}
// 拷贝构造函数
Graph(const Graph& other)
: _vertexs(other._vertexs), _IndexMap(other._IndexMap)
{
_tables.resize(other._tables.size(), nullptr);
// 深拷贝邻接表
for (size_t i = 0; i < other._tables.size(); ++i)
{
GraphEdge* cur = other._tables[i];
GraphEdge* tail = nullptr;
while (cur)
{
GraphEdge* newEdge = new GraphEdge(cur->_w);
newEdge->_src = cur->_src;
newEdge->_dst = cur->_dst;
if (tail == nullptr)
{
_tables[i] = newEdge;
}
else
{
tail->_next = newEdge;
}
tail = newEdge;
cur = cur->_next;
}
}
}
// 移动构造函数
Graph(Graph&& other) noexcept
: _vertexs(std::move(other._vertexs))
, _IndexMap(std::move(other._IndexMap))
, _tables(std::move(other._tables))
{
other._tables.clear();
}
// 析构函数
~Graph()
{
Clear();
}
//清空图
void Clear()
{
for (size_t i = 0; i < _tables.size(); ++i)
{
GraphEdge* cur = _tables[i];
while (cur)
{
GraphEdge* next = cur->_next;
delete cur;
cur = next;
}
_tables[i] = nullptr;
}
_tables.clear();
_vertexs.clear();
_IndexMap.clear();
}
// 拷贝赋值运算符
Graph& operator=(const Graph& other)
{
if (this != &other)
{
Clear();
_vertexs = other._vertexs;
_IndexMap = other._IndexMap;
_tables.resize(other._tables.size(), nullptr);
for (size_t i = 0; i < other._tables.size(); ++i)
{
GraphEdge* cur = other._tables[i];
GraphEdge* tail = nullptr;
while (cur)
{
GraphEdge* newEdge = new GraphEdge(cur->_w);
newEdge->_src = cur->_src;
newEdge->_dst = cur->_dst;
if (tail == nullptr)
{
_tables[i] = newEdge;
}
else
{
tail->_next = newEdge;
}
tail = newEdge;
cur = cur->_next;
}
}
}
return *this;
}
// 移动赋值运算符
Graph& operator=(Graph&& other) noexcept
{
if (this != &other)
{
Clear();
_vertexs = std::move(other._vertexs);
_IndexMap = std::move(other._IndexMap);
_tables = std::move(other._tables);
other._tables.clear();
}
return *this;
}
//添加顶点
size_t AddVertex(const V& vertex)
{
auto it = _IndexMap.find(vertex);
if (it != _IndexMap.end())
{
return it->second;
}
size_t index = _vertexs.size();
_vertexs.push_back(vertex);
_IndexMap[vertex] = index;
_tables.push_back(nullptr);
return index;
}
//确定顶点的下标
size_t GetVertexsIndex(const V& v)
{
auto it = _IndexMap.find(v);
if (it != _IndexMap.end())
{
return it->second;
}
else
{
throw std::invalid_argument("顶点不存在");
}
}
//添加边
//两个顶点一个权值
void AddEdge(const V& src, const V& dst, const W& w)
{
size_t src_m = GetVertexsIndex(src);
size_t dst_m = GetVertexsIndex(dst);
// 创建正向边 src->dst
GraphEdge* eg = new GraphEdge(w);
eg->_src = (int)src_m;
eg->_dst = (int)dst_m;
eg->_next = _tables[src_m];
_tables[src_m] = eg;
// 如果是无向图,还需要添加反向边 dst->src
if (direction == false)
{
GraphEdge* reverse_eg = new GraphEdge(w);
reverse_eg->_src = (int)dst_m;
reverse_eg->_dst = (int)src_m;
reverse_eg->_next = _tables[dst_m];
_tables[dst_m] = reverse_eg;
}
}
// 获取顶点数量
size_t GetVertexCount() const
{
return _vertexs.size();
}
// 获取边数量
size_t GetEdgeCount() const
{
size_t count = 0;
for (size_t i = 0; i < _tables.size(); ++i)
{
GraphEdge* cur = _tables[i];
while (cur)
{
++count;
cur = cur->_next;
}
}
return direction ? count : count / 2;
}
// 广度优先遍历
void BFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
queue<int> q;
q.push(src_m);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
int levelsize = 1;
visited[src_m] = true;
cout << "从顶点 " << src << " 开始的广度优先遍历:" << endl;
while (!q.empty())
{
// 一层一层出
for (size_t i = 0; i < levelsize; ++i)
{
int front = q.front();
q.pop();
cout << front << " : " << _vertexs[front] << endl;
// 把邻接顶点入队列
GraphEdge* cur = _tables[front];
while (cur)
{
if (visited[cur->_dst] == false)
{
q.push(cur->_dst);
visited[cur->_dst] = true;
}
cur = cur->_next;
}
}
printf("\\n");
levelsize = q.size();
}
printf("\\n");
}
// 深度优先遍历
void DFS(const V& src)
{
size_t src_m = GetVertexsIndex(src);
size_t n = _vertexs.size();
vector<bool> visited(n, false);
cout << "从顶点 " << src << " 开始的深度优先遍历:" << endl;
_DFS(src_m, visited);
cout << endl;
}
// 深度优先子函数
void _DFS(size_t src_m, vector<bool>& visited)
{
cout << src_m << " : " << _vertexs[src_m] << endl;
visited[src_m] = true;
// 找src_m相邻的点去深度访问
GraphEdge* cur = _tables[src_m];
while (cur)
{
if (visited[cur->_dst] == false)
{
_DFS(cur->_dst, visited);
}
cur = cur->_next;
}
}
void print()
{
// 顶点与下标的映射
//横下表
for (size_t i = 0; i < _vertexs.size(); ++i)
{
cout << "[" << i << "]" << "->" << _vertexs[i] << endl;
}
cout << endl;
for (size_t i = 0; i < _tables.size(); ++i)
{
cout << _vertexs[i] << "[" << i << "]" << "->";
GraphEdge* cur = _tables[i];
while (cur)
{
cout << "" << _vertexs[cur->_dst] << "[" << cur->_dst << "]" << " [权值:" << cur->_w << "]->";
cur = cur->_next;
}
cout << "nullptr" << endl;
}
cout << endl;
}
private:
vector<V> _vertexs;//顶点的集合
map<V, int> _IndexMap;//顶点映射的下标关系
vector<GraphEdge*> _tables;//邻接表
};
}
UnionFindSet3.h
#pragma once
#include <vector>
using namespace std;
class UnionFindSet
{
public:
// 构造函数:初始时,将数组中元素全部设置为-1
UnionFindSet(size_t size) : _ufs(size, -1) {}
// 给一个元素的编号,找到该元素所在集合的根节点
int FindRoot(int index)
{
// 路径压缩优化:递归实现
if (_ufs[index] < 0) {
return index;
}
return _ufs[index] = FindRoot(_ufs[index]);
}
// 合并两个元素所在的集合
bool Union(int x1, int x2)
{
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
// x1已经与x2在同一个集合
if (root1 == root2) {
return false;
}
// 按秩合并(小树合并到大树):这里使用负数表示树的大小
if (_ufs[root1] > _ufs[root2]) { // root2的树更大(因为值更负)
_ufs[root2] += _ufs[root1];
_ufs[root1] = root2;
}
else {
_ufs[root1] += _ufs[root2];
_ufs[root2] = root1;
}
return true;
}
// 判断两个元素是否属于同一个集合
bool InSet(int x1, int x2)
{
return FindRoot(x1) == FindRoot(x2);
}
// 返回集合的数量(数组中负数的个数)
size_t Count() const
{
size_t count = 0;
for (auto e : _ufs) {
if (e < 0) {
++count;
}
}
return count;
}
// 获取指定集合的大小(绝对值的负数个数)
int GetSetSize(int index)
{
int root = FindRoot(index);
return -_ufs[root];
}
private:
vector<int> _ufs; // 负数表示根节点,其绝对值表示集合大小;正数表示父节点索引
};
test1.cpp
#define _CRT_SECURE_NO_WARNINGS
#include"Graph.h"
#include"UnionFindSet.h"
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
//邻接矩阵和邻接表的构造
void test1()
{
std::cout << "========== 邻接表图测试 ==========" << std::endl;
// 测试1: 使用示例中的方式
std::cout << "\\n测试1: 基础邻接表图" << std::endl;
std::string a[] = { "歌者", "观察者", "理想者", "幻想者" };
ALGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
// 测试2: 使用初始化列表构造
std::cout << "\\n测试2: 使用初始化列表构造" << std::endl;
ALGraph::Graph<std::string, int> g2(
{ "A", "B", "C", "D" },
{
std::make_tuple("A", "B", 10),
std::make_tuple("A", "C", 20),
std::make_tuple("B", "D", 30),
std::make_tuple("C", "D", 40)
}
);
g2.print();
std::cout << "顶点数量: " << g2.GetVertexCount() << std::endl;
std::cout << "边数量: " << g2.GetEdgeCount() << std::endl;
// 测试3: 邻接矩阵图
std::cout << "\\n========== 邻接矩阵图测试 ==========" << std::endl;
AMGraph::Graph<std::string, int> g3(a, 4);
g3.AddEdge("歌者", "观察者", 50);
g3.AddEdge("歌者", "理想者", 30);
g3.AddEdge("歌者", "幻想者", 4000);
g3.AddEdge("观察者", "理想者", 60);
g3.AddEdge("观察者", "幻想者", 60);
g3.AddEdge("理想者", "幻想者", 400);
g3.Print();
// 测试4: 使用初始化列表构造邻接矩阵图
std::cout << "\\n测试4: 初始化列表构造邻接矩阵图" << std::endl;
AMGraph::Graph<std::string, int> g4(
{ "X", "Y", "Z" },
{
std::make_tuple("X", "Y", 100),
std::make_tuple("Y", "Z", 200),
std::make_tuple("Z", "X", 300)
}
);
g4.Print();
// 测试5: 无向图
std::cout << "\\n测试5: 无向图" << std::endl;
ALGraph::Graph<std::string, int, false> g5(
{ "A", "B", "C" },
{
std::make_tuple("A", "B", 5),
std::make_tuple("B", "C", 8),
std::make_tuple("C", "A", 10)
}
);
g5.print();
std::cout << "无向图边数量: " << g5.GetEdgeCount() << std::endl;
// 测试6: 有向图
std::cout << "\\n测试6: 有向图" << std::endl;
ALGraph::Graph<std::string, int, true> g6(
{ "A", "B", "C" },
{
std::make_tuple("A", "B", 5),
std::make_tuple("B", "C", 8),
std::make_tuple("C", "A", 10)
}
);
g6.print();
std::cout << "有向图边数量: " << g6.GetEdgeCount() << std::endl;
// 测试7: 动态添加顶点和边
std::cout << "\\n测试7: 动态添加顶点和边" << std::endl;
ALGraph::Graph<char, int> g7;
g7.AddVertex('A');
g7.AddVertex('B');
g7.AddVertex('C');
g7.AddVertex('D');
g7.AddEdge('A', 'B', 1);
g7.AddEdge('B', 'C', 2);
g7.AddEdge('C', 'D', 3);
g7.AddEdge('D', 'A', 4);
g7.print();
std::cout << "最终顶点数量: " << g7.GetVertexCount() << std::endl;
std::cout << "最终边数量: " << g7.GetEdgeCount() << std::endl;
std::cout << "\\n所有测试完成!" << std::endl;
}
//邻接矩阵的广度遍历
void test2()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
AMGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.Print();
g1.BFS("歌者");
cout << endl;
g1.BFS("观察者");
cout << endl;
g1.BFS("理想者");
cout << endl;
g1.BFS("幻想者");
cout << endl;
}
//邻接矩阵的深度遍历
void test3()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
AMGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.Print();
g1.DFS("歌者");
cout << endl;
g1.DFS("观察者");
cout << endl;
g1.DFS("理想者");
cout << endl;
g1.DFS("幻想者");
cout << endl;
}
//邻接表的广度遍历
void test4()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
ALGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.BFS("歌者");
cout << endl;
g1.BFS("观察者");
cout << endl;
g1.BFS("理想者");
cout << endl;
g1.BFS("幻想者");
cout << endl;
}
//邻接表的深度遍历
void test5()
{
string a[] = { "歌者", "观察者", "理想者", "幻想者" };
ALGraph::Graph<std::string, int> g1(a, 4);
g1.AddEdge("歌者", "观察者", 50);
g1.AddEdge("歌者", "理想者", 30);
g1.AddEdge("歌者", "幻想者", 4000);
g1.AddEdge("观察者", "理想者", 60);
g1.AddEdge("观察者", "幻想者", 60);
g1.AddEdge("理想者", "幻想者", 400);
g1.print();
g1.DFS("歌者");
cout << endl;
g1.DFS("观察者");
cout << endl;
g1.DFS("理想者");
cout << endl;
g1.DFS("幻想者");
cout << endl;
}
//两种最小生成树测试
void testMintree()
{
const char* str = "abcdefghi";
AMGraph::Graph<char, int> g(str, strlen(str));
g.AddEdge('a', 'b', 4);
g.AddEdge('a', 'h', 8);
g.AddEdge('a', 'h', 9);
g.AddEdge('b', 'c', 8);
g.AddEdge('b', 'h', 11);
g.AddEdge('c', 'i', 2);
g.AddEdge('c', 'f', 4);
g.AddEdge('c', 'd', 7);
g.AddEdge('d', 'f', 14);
g.AddEdge('d', 'e', 9);
g.AddEdge('e', 'f', 10);
g.AddEdge('f', 'g', 2);
g.AddEdge('g', 'h', 1);
g.AddEdge('g', 'i', 6);
g.AddEdge('h', 'i', 7);
AMGraph::Graph<char, int> kminTree;
cout << "Kruskal:" << g.Kruskal(kminTree) << endl;
kminTree.Print();
AMGraph::Graph<char, int> pminTree;
cout << "Prim:" << g.Prim_Set(pminTree, 'a') << endl;
cout << "Prim:" << g.Prim_Vector(pminTree, 'a') << endl;
pminTree.Print();
}
void TestGraphDijkstra()
{
const char* str1 = "syztx";
AMGraph::Graph<char, int, INT_MAX, true> g1(str1, strlen(str1));
g1.AddEdge('s', 't', 10);
g1.AddEdge('s', 'y', 5);
g1.AddEdge('y', 't', 3);
g1.AddEdge('y', 'x', 9);
g1.AddEdge('y', 'z', 2);
g1.AddEdge('z', 's', 7);
g1.AddEdge('z', 'x', 6);
g1.AddEdge('t', 'y', 2);
g1.AddEdge('t', 'x', 1);
g1.AddEdge('x', 'z', 4);
vector<int> dist1;
vector<int> parentPath1;
g1.Dijkstra('s', dist1, parentPath1);
g1.PrinrtShotPath('s', dist1, parentPath1);
// 图中带有负权路径时,贪心策略则失效了。
// 测试结果可以看到s->t->y之间的最短路径没更新出来
const char* str2 = "sytx";
AMGraph::Graph<char, int, INT_MAX, true> g2(str2, strlen(str2));
g2.AddEdge('s', 't', 10);
g2.AddEdge('s', 'y', 5);
g2.AddEdge('t', 'y', -7);
g2.AddEdge('y', 'x', 3);
vector<int> dist2;
vector<int> parentPath2;
g2.Dijkstra('s', dist2, parentPath2);
g2.PrinrtShotPath('s', dist2, parentPath2);
}
void TestGraphBellmanFord()
{
const char* str = "syztx";
AMGraph::Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 6);
g.AddEdge('s', 'y', 7);
g.AddEdge('y', 'z', 9);
g.AddEdge('y', 'x', -3);
g.AddEdge('z', 's', 2);
g.AddEdge('z', 'x', 7);
g.AddEdge('t', 'x', 5);
g.AddEdge('t', 'y', 8);
g.AddEdge('t', 'z', -4);
// 5.3 多源最短路径–Floyd-Warshall算法
// Floyd-Warshall算法是解决任意两点间的最短路径的一种算法。
// Floyd算法考虑的是一条最短路径的中间节点,即简单路径p={v1,v2,…,vn}上除v1和vn的任意节点。
// 设k是p的一个中间节点,那么从i到j的最短路径p就被分成i到k和k到j的两段最短路径p1,p2。
// p1是从i到k且中间节点属于{1,2,…,k-1}取得的一条最短路径。
// p2是从k到j且中间节点属于{1,2,…,k-1}取得的一条最短路径。
g.AddEdge('x', 't', -2);
vector<int> dist;
vector<int> parentPath;
if (g.BellmanFord('s', dist, parentPath))
{
g.PrinrtShotPath('s', dist, parentPath);
}
else
{
cout << "存在负权回路" << endl;
}
// 微调图结构,带有负权回路的测试
/*
const char* str = "syztx";
Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 6);
g.AddEdge('s', 'y', 7);
g.AddEdge('y', 'x', -3);
g.AddEdge('y', 'z', 9);
g.AddEdge('y', 'x', -3);
g.AddEdge('y', 's', 1); // 新增
g.AddEdge('z', 's', 2);
g.AddEdge('z', 'x', 7);
g.AddEdge('t', 'x', 5);
g.AddEdge('t', 'y', -8); // 更改
g.AddEdge('t', 'z', -4);
g.AddEdge('x', 't', -2);
vector<int> dist;
vector<int> parentPath;
if (g.BellmanFord('s', dist, parentPath))
{
g.PrinrtShotPath('s', dist, parentPath);
}
else
{
cout << "存在负权回路" << endl;
}
*/
}
void TestFloydWarShall()
{
const char* str = "12345";
AMGraph::Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('1', '2', 3);
g.AddEdge('1', '3', 8);
g.AddEdge('1', '5', -4);
g.AddEdge('2', '4', 1);
g.AddEdge('2', '5', 7);
g.AddEdge('3', '2', 4);
g.AddEdge('4', '1', 2);
g.AddEdge('4', '3', -5);
g.AddEdge('5', '4', 6);
vector<vector<int>> vvDist;
vector<vector<int>> vvParentPath;
g.FloydWarShall(vvDist, vvParentPath);
// 打印任意两点之间的最短路径
for (size_t i = 0; i < strlen(str); ++i)
{
g.PrinrtShotPath(str[i], vvDist[i], vvParentPath[i]);
cout << endl;
}
}
int main()
{
//test1();
//test2();
//test3();
//test4();
//test5();
//testMintree();
//TestGraphDijkstra();
//TestGraphBellmanFord();
//TestFloydWarShall();
return 0;
}
关于图的介绍到这里结束了,如果你喜欢请点个赞,如果你期待这个请订阅我的数据结构专栏
封面图自取:





