一。图的基本概念
图是由顶点集合及顶点间的关系组成的一种数据结构:G = (V, E),其中:
顶点集合 V = {x|x 属于某个数据对象集} 是有穷非空集合;
本文系统讲解了图数据结构的核心内容,包括基本概念、邻接矩阵与邻接表两种存储方式、广度优先与深度优先遍历算法。重点阐述了最小生成树的 Kruskal 与 Prim 算法,以及单源和多源最短路径的 Dijkstra、Bellman-Ford 和 Floyd-Warshall 算法。文中提供了完整的 C++ 模板代码实现,涵盖类定义、辅助函数及测试用例,适合算法学习与工程参考。

图是由顶点集合及顶点间的关系组成的一种数据结构:G = (V, E),其中:
顶点集合 V = {x|x 属于某个数据对象集} 是有穷非空集合;
E = {(x,y)|x,y 属于 V} 或者 E = {|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 的一条边 (弧),和是两条不同的边,比如下图 G3 和 G4 为有向图。在无向图中,顶点对 (x, y) 是无序的,顶点对 (x,y) 称为顶点 x 和顶点 y 相关联的一条边,这条边没有特定方向,(x, y) 和 (y,x) 是同一条边,比如下图 G1 和 G2 为无向图。

完全图:在有 n 个顶点的无向图中,若有 n * (n-1)/2 条边,即任意两个顶点之间有且仅有一条边,则称此图为无向完全图,比如上图 G1;在 n 个顶点的有向图中,若有 n * (n-1) 条边,即任意两个顶点之间有且仅有方向相反的边,则称此图为有向完全图,比如上图 G4
邻接顶点:在无向图中 G 中,若 (u, v) 是 E(G) 中的一条边,则称 u 和 v 互为邻接顶点,并称边 (u,v) 依附于顶点 u 和 v;在有向图 G 中,若是 E(G) 中的一条边,则称顶点 u 邻接到 v,顶点 v 邻接自顶点 u,并称边与顶点 u 和顶点 v 相关联
顶点的度:顶点 v 的度是指与它相关联的边的条数,记作 deg(v)。在有向图中,顶点的度等于该顶点的入度与出度之和,其中顶点 v 的入度是以 v 为终点的有向边的条数,记作 indeg(v); 顶点 v 的出度是以 v 为起始点的有向边的条数,记作 outdeg(v)。因此:deg(v) = indeg(v) + outdeg(v)。注意:对于无向图,顶点的度等于该顶点的入度和出度,即deg(v) = indeg(v) = outdeg(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,因此邻接矩阵 (二维数组) 即是:先用一个数组将定点保存,然后采用矩阵来表示节点与节点之间的关系

注意:

namespace matrix {
template<class V, class W, W MAX_W = INT_MAX, bool Direction = false>
class Graph {
typedef Graph<V, W, MAX_W, Direction> Self;
public:
//图的创建
//1.IO 输入->不方便测试,oj 中更适合
//2.图结构关系写到文件,读取文件
//3.手动添加边
Graph() = default;
Graph(const V* a, size_t 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 GetVertexIndex(const V& v) {
auto it = _indexMap.find(v);
if (it != _indexMap.end()) {
return it->second;
} else {
//assert(false);
throw invalid_argument("顶点不存在");
return -1;
}
}
void _AddEdge(size_t srci, size_t dsti, const W& w) {
_matrix[srci][dsti] = w;
//无向图
if (Direction == false) {
_matrix[dsti][srci] = w;
}
}
void AddEdge(const V& src, const V& dst, const W& w) {
size_t srci = GetVertexIndex(src);
size_t dsti = GetVertexIndex(dst);
_AddEdge(srci, dsti, 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 < _matrix.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) {
//cout << _matrix[i][j] << " ";
if (_matrix[i][j] == MAX_W) {
//cout << "* ";
printf("%4c", '*');
} else {
//cout << _matrix[i][j] << " ";
printf("%4d", _matrix[i][j]);
}
}
cout << endl;
}
cout << endl;
}
private:
vector<V> _vertexs; //顶点集合
map<V, int> _indexMap; //顶点映射下标
vector<vector<W>> _matrix; //邻接矩阵
};
}
void TestGraph1() {
Graph<char, int> g("0123", 4);
//Graph<char, int, true> g("0123", 4);
g.AddEdge('0', '1', 1);
g.AddEdge('0', '3', 4);
g.AddEdge('1', '3', 2);
g.AddEdge('1', '2', 9);
g.AddEdge('2', '3', 8);
g.AddEdge('2', '1', 5);
g.AddEdge('2', '0', 3);
g.AddEdge('3', '2', 6);
g.Print();
}

邻接矩阵总结:
邻接表:使用数组表示顶点的集合,使用链表表示边的关系
1.无向图邻接表存储

注意:无向图中同一条边在邻接表中出现了两次。如果想知道顶点 vi 的度,只需要知道顶点 vi 边链表集合中结点的数目即可
2.有向图邻接表存储

注意:有向图中每条边在邻接表中只出现一次,与顶点 vi 对应的邻接表所含结点的个数,就是该顶点的出度,也称出度表,要得到 vi 顶点的入度,必须检测其他所有顶点对应的边链表,看有多少边顶点的 dst 取值是 i
namespace link_table {
template<class W>
struct Edge {
//int _srci;
int _dsti; //目标点的下标
W _w; //权值
Edge<W>* _next;
Edge(int dsti, const W& w) :_dsti(dsti), _w(w), _next(nullptr) {
}
};
template<class V, class W, bool Direction = false>
class Graph {
typedef Edge<W> Edge;
public:
Graph(const V* a, size_t 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);
}
size_t GetVertexIndex(const V& v) {
auto it = _indexMap.find(v);
if (it != _indexMap.end()) {
return it->second;
} else {
//assert(false);
throw invalid_argument("顶点不存在");
return -1;
}
}
void AddEdge(const V& src, const V& dst, const W& w) {
size_t srci = GetVertexIndex(src);
size_t dsti = GetVertexIndex(dst);
Edge* eg = new Edge(dsti, w);
eg->_next = _tables[srci];
_tables[srci] = eg;
if (Direction == false) {
Edge* eg = new Edge(srci, w);
eg->_next = _tables[dsti];
_tables[dsti] = 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 << "]->";
Edge* cur = _tables[i];
while (cur) {
cout << "[" << _vertexs[cur->_dsti] << ":" << cur->_dsti << ":" << cur->_w << "]->";
cur = cur->_next;
}
cout << "nullptr" << endl;
}
}
private:
vector<V> _vertexs; //顶点集合
map<V, int> _indexMap; //顶点映射下标
vector<Edge*> _tables; //邻接表
};
}
void TestGraph2() {
string a[] = { "张三", "李四", "王五", "赵六" };
//Graph<string, int, true> g1(a, 4);
Graph<string, int> g1(a, 4);
g1.AddEdge("张三", "李四", 100);
g1.AddEdge("张三", "王五", 200);
g1.AddEdge("王五", "赵六", 30);
g1.Print();
}

邻接表总结:

void BFS(const V& src) {
size_t srci = GetVertexIndex(src);
//队列和标记数组
queue<int> q;
vector<bool> visited(_vertexs.size(), false);
q.push(srci);
visited[srci] = true;
int levelSize = 1;
size_t n = _vertexs.size();
while (!q.empty()) {
//一层一层出
for (int i = 0; i < levelSize; ++i) {
int front = q.front();
q.pop();
cout << front << ":" << _vertexs[front] << " ";
//把 front 顶点的邻接顶点入队列
for (size_t i = 0; i < n; ++i) {
if (_matrix[front][i] != MAX_W) {
if (visited[i] == false) {
q.push(i);
visited[i] = true;
}
}
}
}
cout << endl;
levelSize = q.size();
}
cout << endl;
}
void TestBDFS() {
string a[] = { "张三", "李四", "王五", "赵六", "周七" };
Graph<string, int> g1(a, sizeof(a) / sizeof(string));
g1.AddEdge("张三", "李四", 100);
g1.AddEdge("张三", "王五", 200);
g1.AddEdge("王五", "赵六", 30);
g1.AddEdge("王五", "周七", 30);
g1.Print();
g1.BFS("张三");
}


void _DFS(size_t srci, vector<bool>& visited) {
cout << srci << ":" << _vertexs[srci] << endl;
visited[srci] = true;
//找一个和 srci 相邻的没有访问过的点,去深度遍历
for (size_t i = 0; i < _vertexs.size(); ++i) {
if (_matrix[srci][i] != MAX_W && visited[i] == false) {
_DFS(i, visited);
}
}
}
void DFS(const V& src) {
size_t srci = GetVertexIndex(src);
vector<bool> visited(_vertexs.size(), false);
_DFS(srci, visited);
}
void TestBDFS() {
string a[] = { "张三", "李四", "王五", "赵六", "周七" };
Graph<string, int> g1(a, sizeof(a) / sizeof(string));
g1.AddEdge("张三", "李四", 100);
g1.AddEdge("张三", "王五", 200);
g1.AddEdge("王五", "赵六", 30);
g1.AddEdge("王五", "周七", 30);
g1.Print();
g1.DFS("张三");
}

连通图中的每一棵生成树,都是原图的一个极大无环子图,即:从其中删去任何一条边,生成树就不在连通;反之,在其中引入任何一条新边,都会形成一条回路
若连通图由 n 个顶点组成,则其生成树必含 n 个顶点和 n-1 条边。因此构造最小生成树的准则有三条:
Kruskal 算法 (克鲁斯卡尔算法) 任给一个有 n 个顶点的连通网络 N={V,E},首先构造一个由这 n 个顶点组成、不含任何边的图 G={V,NULL},其中每个顶点自成一个连通分量,其次不断从 E 中取出权值最小的一条边 (若有多条任取其一),若该边的两个顶点来自不同的连通分量,则将此边加入到 G 中。如此重复,直到所有顶点在同一个连通分量上为止
核心:每次迭代时,选出一条具有最小权值,且两端点不在同一连通分量上的边,加入生成树

struct Edge {
size_t _srci;
size_t _dsti;
W _w;
Edge(size_t srci, size_t dsti, const W& w) :_srci(srci), _dsti(dsti), _w(w) {
}
bool operator>(const Edge& e) const {
return _w > e._w;
}
};
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, MAX_W);
}
priority_queue<Edge, vector<Edge>, greater<Edge>> minque;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (i < j && _matrix[i][j] != MAX_W) {
minque.push(Edge(i, j, _matrix[i][j]));
}
}
}
cout << "Kruskal 开始选边:" << endl;
//选出 n-1 条边
int size = 0;
W totalW = W();
UnionFindSet ufs(n);
while (!minque.empty()) {
Edge min = minque.top();
minque.pop();
if (!ufs.InSet(min._srci, min._dsti)) {
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
minTree._AddEdge(min._srci, min._dsti, min._w);
ufs.Union(min._srci, min._dsti);
++size;
totalW += min._w;
} else {
cout << "构成环";
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
}
}
cout << endl;
if (size == n - 1) {
return totalW;
} else {
return W();
}
}
void TestGraphMinTree() {
const char str[] = "abcdefghi";
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);
Graph<char, int> kminTree;
cout << "Kruskal:" << g.Kruskal(kminTree) << endl;
kminTree.Print();
cout << endl;
}

Prim 算法 (普里姆算法)

W Prim(Self& minTree, const W& src) {
size_t srci = GetVertexIndex(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, MAX_W);
}
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>> minq;
//将 srci 连接的边添加到队列中
for (size_t i = 0; i < n; ++i) {
if (_matrix[srci][i] != MAX_W) {
minq.push(Edge(srci, i, _matrix[srci][i]));
}
}
cout << "Prim 开始选边:" << endl;
int size = 0;
W totalW = W();
while (!minq.empty()) {
Edge min = minq.top();
minq.pop();
if (X[min._dsti]) {
cout << "构成环";
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
} else {
minTree._AddEdge(min._srci, min._dsti, min._w);
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
X[min._dsti] = true;
Y[min._dsti] = false;
++size;
totalW += min._w;
if (size == n - 1) break;
for (size_t i = 0; i < n; ++i) {
if (_matrix[min._dsti][i] != MAX_W && Y[i]) {
minq.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
}
}
}
}
cout << endl;
if (size == n - 1) {
return totalW;
} else {
return W();
}
}
void TestGraphMinTree() {
const char str[] = "abcdefghi";
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);
Graph<char, int> pminTree;
cout << "Prim:" << g.Prim(pminTree, 'a') << endl;
pminTree.Print();
}

最短路径问题:从在带权有向图 G 中的某一顶点出发,找出一条通往另一顶点的最短路径,最短也就是沿路径各边的权值总和达到最小
单源最短路径问题:给定一个图 G = (V, E),求源结点 s ∈ V 到图中每个结点 v ∈ 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 算法 (迪杰斯特拉算法) 存在的问题是不支持图中带负权路径,如果带有负权路径,则可能会找不到一些路径的最短路径

//时间复杂度:O(N^2),空间复杂度:O(N)
void Dijkstra(const V& src, vector<W>& dist, vector<int>& pPath) {
size_t srci = GetVertexIndex(src);
size_t n = _vertexs.size();
dist.resize(n, MAX_W);
pPath.resize(n, -1);
dist[srci] = 0;
pPath[srci] = srci;
//已经确定最短路径的顶点集合
vector<bool> S(n, false);
for (size_t j = 0; j < n; ++j) {
//选出最短路径顶点且不在 S 更新其他路径
int u = 0;
W min = MAX_W;
for (size_t i = 0; i < n; ++i) {
if (S[i] == false && dist[i] < min) {
u = i;
min = dist[i];
}
}
S[u] = true;
//松弛更新
for (size_t v = 0; v < n; ++v) {
if (S[v] == false && _matrix[u][v] != MAX_W && dist[u] + _matrix[u][v] < dist[v]) {
dist[v] = dist[u] + _matrix[u][v];
pPath[v] = u;
}
}
}
}
void TestGraphDijkstra() {
const char* str = "syztx";
Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 10);
g.AddEdge('s', 'y', 5);
g.AddEdge('y', 't', 3);
g.AddEdge('y', 'x', 9);
g.AddEdge('y', 'z', 2);
g.AddEdge('z', 's', 7);
g.AddEdge('z', 'x', 6);
g.AddEdge('t', 'y', 2);
g.AddEdge('t', 'x', 1);
g.AddEdge('x', 'z', 4);
vector<int> dist;
vector<int> parentPath;
g.Dijkstra('s', dist, parentPath);
g.PrintShortPath('s', dist, parentPath);
}

Dijkstra 算法只能用来解决正权图的单源最短路径问题,但有些题目会出现负权图。这时这个算法就不能帮助我们解决问题了,而 bellman—ford 算法 (贝尔曼 - 福特算法) 可以解决负权图的单源最短路径问题。它的优点是可以解决有负权边的单源最短路径问题,而且可以用来判断是否有负权回路。它也有明显的缺点,它的时间复杂度 O(N*E) (N 是点数,E 是边数) 普遍是要高于 Dijkstra 算法 O(N²) 的。**像这里 如果我们使用邻接矩阵实现,那么遍历所有边的数量的时间复杂度就是 O(N^3),**这里也可以看出来 Bellman-Ford 就是一种暴力求解更新

//时间复杂度:O(N^3),空间复杂度:O(N)
bool BellmanFord(const V& src, vector<W>& dist, vector<int>& pPath) {
size_t srci = GetVertexIndex(src);
size_t n = _vertexs.size();
// vector<W> dist,记录 srci-其他顶点最短路径权值数组
dist.resize(n, MAX_W);
// vector<int> pPath 记录 srci-其他顶点最短路径父顶点数组
pPath.resize(n, -1);
// 先更新 srci->srci 为最小值
dist[srci] = W();
for (size_t k = 0; k < n; ++k) {
bool updata = false;
cout << "更新第" << k << "轮:" << endl;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j]) {
updata = true;
cout << _vertexs[i] << "->" << _vertexs[j] << ":" << _matrix[i][j] << endl;
dist[j] = dist[i] + _matrix[i][j];
pPath[j] = i;
}
}
}
//如果这个轮次没有更新出最短路径,后续轮次就不需要再走
if (updata == false) break;
}
//如果还能更新就是带负权回路
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j]) {
return false;
}
}
}
return true;
}
void TestGraphBellmanFord() {
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', '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', '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.PrintShortPath('s', dist, parentPath);
} else {
cout << "存在负权回路" << endl;
}
}

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 算法本质是三维动态规划,D[i][j][k] 表示从点 i 到点 j 只经过 0 到 k 个点最短路径,然后建立 起转移方程,然后通过空间优化,优化掉最后一维度,变成一个最短路径的迭代算法,最后即得到所有点的最短路径

void FloydWarShall(vector<vector<W>>& vvDist, vector<vector<int>>& vvpPath) {
size_t n = _vertexs.size();
vvDist.resize(n);
vvpPath.resize(n);
for (size_t i = 0; i < n; ++i) {
vvDist[i].resize(n, MAX_W);
vvpPath[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) {
vvDist[i][j] = _matrix[i][j];
vvpPath[i][j] = i;
}
if (i == j) {
vvDist[i][j] = 0;
}
}
}
//最短路径的更新
for (size_t k = 0; k < n; ++k) {
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (vvDist[i][k] != MAX_W && vvDist[k][j] != MAX_W && vvDist[i][k] + vvDist[k][j] < vvDist[i][j]) {
vvDist[i][j] = vvDist[i][k] + vvDist[k][j];
vvpPath[i][j] = vvpPath[k][j];
}
}
}
}
}
void TestFloydWarShall() {
const char* str = "12345";
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.PrintShortPath(str[i], vvDist[i], vvParentPath[i]);
cout << endl;
}
}

#pragma once
#include<vector>
class UnionFindSet {
public:
UnionFindSet(size_t n) :_ufs(n, -1) {
}
int FindRoot(int x) {
int root = x;
while (_ufs[root] >= 0) root = _ufs[root];
//路径压缩
while (_ufs[x] >= 0) {
int parent = _ufs[x];
_ufs[x] = root;
x = parent;
}
return root;
}
bool Union(int x1, int x2) {
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
if (root1 == root2)//x1 和 x2 本来就在一个集合中
return false;
//数据量小的向大的合并
if (abs(_ufs[root1]) < abs(_ufs[root2])) swap(root1, root2);
_ufs[root1] += _ufs[root2];
_ufs[root2] = root1;
return true;
}
bool InSet(int x1, int x2) {
return FindRoot(x1) == FindRoot(x2);
}
size_t SetSize() {
size_t n = 0;
for (auto& e : _ufs) {
if (e < 0) ++n;
}
return n;
}
private:
vector<int> _ufs;
};
void TestUnionFindSet() {
UnionFindSet ufs(10);
ufs.Union(8, 9);
ufs.Union(7, 8);
ufs.Union(6, 7);
ufs.Union(5, 6);
ufs.Union(4, 5);
}
#pragma once
#include<vector>
#include<string>
#include<map>
#include<queue>
#include<set>
#include<functional>
namespace matrix {
template<class V, class W, W MAX_W = INT_MAX, bool Direction = false>
class Graph {
typedef Graph<V, W, MAX_W, Direction> Self;
public:
//图的创建
//1.IO 输入->不方便测试,oj 中更适合
//2.图结构关系写到文件,读取文件
//3.手动添加边
Graph() = default;
Graph(const V* a, size_t 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 GetVertexIndex(const V& v) {
auto it = _indexMap.find(v);
if (it != _indexMap.end()) {
return it->second;
} else {
//assert(false);
throw invalid_argument("顶点不存在");
return -1;
}
}
void _AddEdge(size_t srci, size_t dsti, const W& w) {
_matrix[srci][dsti] = w;
//无向图
if (Direction == false) {
_matrix[dsti][srci] = w;
}
}
void AddEdge(const V& src, const V& dst, const W& w) {
size_t srci = GetVertexIndex(src);
size_t dsti = GetVertexIndex(dst);
_AddEdge(srci, dsti, 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 < _matrix.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) {
//cout << _matrix[i][j] << " ";
if (_matrix[i][j] == MAX_W) {
//cout << "* ";
printf("%4c", '*');
} else {
//cout << _matrix[i][j] << " ";
printf("%4d", _matrix[i][j]);
}
}
cout << endl;
}
cout << endl;
}
void BFS(const V& src) {
size_t srci = GetVertexIndex(src);
//队列和标记数组
queue<int> q;
vector<bool> visited(_vertexs.size(), false);
q.push(srci);
visited[srci] = true;
int levelSize = 1;
size_t n = _vertexs.size();
while (!q.empty()) {
//一层一层出
for (int i = 0; i < levelSize; ++i) {
int front = q.front();
q.pop();
cout << front << ":" << _vertexs[front] << " ";
//把 front 顶点的邻接顶点入队列
for (size_t i = 0; i < n; ++i) {
if (_matrix[front][i] != MAX_W) {
if (visited[i] == false) {
q.push(i);
visited[i] = true;
}
}
}
}
cout << endl;
levelSize = q.size();
}
cout << endl;
}
void _DFS(size_t srci, vector<bool>& visited) {
cout << srci << ":" << _vertexs[srci] << endl;
visited[srci] = true;
//找一个和 srci 相邻的没有访问过的点,去深度遍历
for (size_t i = 0; i < _vertexs.size(); ++i) {
if (_matrix[srci][i] != MAX_W && visited[i] == false) {
_DFS(i, visited);
}
}
}
void DFS(const V& src) {
size_t srci = GetVertexIndex(src);
vector<bool> visited(_vertexs.size(), false);
_DFS(srci, visited);
}
struct Edge {
size_t _srci;
size_t _dsti;
W _w;
Edge(size_t srci, size_t dsti, const W& w) :_srci(srci), _dsti(dsti), _w(w) {
}
bool operator>(const Edge& e) const {
return _w > e._w;
}
};
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, MAX_W);
}
priority_queue<Edge, vector<Edge>, greater<Edge>> minque;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (i < j && _matrix[i][j] != MAX_W) {
minque.push(Edge(i, j, _matrix[i][j]));
}
}
}
cout << "Kruskal 开始选边:" << endl;
//选出 n-1 条边
int size = 0;
W totalW = W();
UnionFindSet ufs(n);
while (!minque.empty()) {
Edge min = minque.top();
minque.pop();
if (!ufs.InSet(min._srci, min._dsti)) {
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
minTree._AddEdge(min._srci, min._dsti, min._w);
ufs.Union(min._srci, min._dsti);
++size;
totalW += min._w;
} else {
cout << "构成环";
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
}
}
cout << endl;
if (size == n - 1) {
return totalW;
} else {
return W();
}
}
W Prim(Self& minTree, const W& src) {
size_t srci = GetVertexIndex(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, MAX_W);
}
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>> minq;
//将 srci 连接的边添加到队列中
for (size_t i = 0; i < n; ++i) {
if (_matrix[srci][i] != MAX_W) {
minq.push(Edge(srci, i, _matrix[srci][i]));
}
}
cout << "Prim 开始选边:" << endl;
int size = 0;
W totalW = W();
while (!minq.empty()) {
Edge min = minq.top();
minq.pop();
if (X[min._dsti]) {
cout << "构成环";
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
} else {
minTree._AddEdge(min._srci, min._dsti, min._w);
cout << _vertexs[min._srci] << "->" << _vertexs[min._dsti] << ":" << min._w << endl;
X[min._dsti] = true;
Y[min._dsti] = false;
++size;
totalW += min._w;
if (size == n - 1) break;
for (size_t i = 0; i < n; ++i) {
if (_matrix[min._dsti][i] != MAX_W && Y[i]) {
minq.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
}
}
}
}
cout << endl;
if (size == n - 1) {
return totalW;
} else {
return W();
}
}
void PrintShortPath(const V& src, const vector<W>& dist, const vector<int>& pPath) {
size_t srci = GetVertexIndex(src);
size_t n = _vertexs.size();
for (size_t i = 0; i < n; ++i) {
if (i != srci) {
//找出 i 顶点的路径
vector<int> path;
size_t parenti = i;
while (parenti != srci) {
path.push_back(parenti);
parenti = pPath[parenti];
}
path.push_back(srci);
reverse(path.begin(), path.end());
for (auto index : path) {
cout << _vertexs[index] << "->";
}
cout << "权值和:" << dist[i] << endl;
}
}
}
//时间复杂度:O(N^2),空间复杂度:O(N)
void Dijkstra(const V& src, vector<W>& dist, vector<int>& pPath) {
size_t srci = GetVertexIndex(src);
size_t n = _vertexs.size();
dist.resize(n, MAX_W);
pPath.resize(n, -1);
dist[srci] = 0;
pPath[srci] = srci;
//已经确定最短路径的顶点集合
vector<bool> S(n, false);
for (size_t j = 0; j < n; ++j) {
//选出最短路径顶点且不在 S 更新其他路径
int u = 0;
W min = MAX_W;
for (size_t i = 0; i < n; ++i) {
if (S[i] == false && dist[i] < min) {
u = i;
min = dist[i];
}
}
S[u] = true;
//松弛更新
for (size_t v = 0; v < n; ++v) {
if (S[v] == false && _matrix[u][v] != MAX_W && dist[u] + _matrix[u][v] < dist[v]) {
dist[v] = dist[u] + _matrix[u][v];
pPath[v] = u;
}
}
}
}
//时间复杂度:O(N^3),空间复杂度:O(N)
bool BellmanFord(const V& src, vector<W>& dist, vector<int>& pPath) {
size_t srci = GetVertexIndex(src);
size_t n = _vertexs.size();
// vector<W> dist,记录 srci-其他顶点最短路径权值数组
dist.resize(n, MAX_W);
// vector<int> pPath 记录 srci-其他顶点最短路径父顶点数组
pPath.resize(n, -1);
// 先更新 srci->srci 为最小值
dist[srci] = W();
for (size_t k = 0; k < n; ++k) {
bool updata = false;
cout << "更新第" << k << "轮:" << endl;
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j]) {
updata = true;
cout << _vertexs[i] << "->" << _vertexs[j] << ":" << _matrix[i][j] << endl;
dist[j] = dist[i] + _matrix[i][j];
pPath[j] = i;
}
}
}
//如果这个轮次没有更新出最短路径,后续轮次就不需要再走
if (updata == false) break;
}
//如果还能更新就是带负权回路
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j]) {
return false;
}
}
}
return true;
}
void FloydWarShall(vector<vector<W>>& vvDist, vector<vector<int>>& vvpPath) {
size_t n = _vertexs.size();
vvDist.resize(n);
vvpPath.resize(n);
for (size_t i = 0; i < n; ++i) {
vvDist[i].resize(n, MAX_W);
vvpPath[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) {
vvDist[i][j] = _matrix[i][j];
vvpPath[i][j] = i;
}
if (i == j) {
vvDist[i][j] = 0;
}
}
}
//最短路径的更新
for (size_t k = 0; k < n; ++k) {
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (vvDist[i][k] != MAX_W && vvDist[k][j] != MAX_W && vvDist[i][k] + vvDist[k][j] < vvDist[i][j]) {
vvDist[i][j] = vvDist[i][k] + vvDist[k][j];
vvpPath[i][j] = vvpPath[k][j];
}
}
}
}
}
private:
vector<V> _vertexs; //顶点集合
map<V, int> _indexMap; //顶点映射下标
vector<vector<W>> _matrix; //邻接矩阵
};
void TestGraph1() {
Graph<char, int> g("0123", 4);
//Graph<char, int, true> g("0123", 4);
g.AddEdge('0', '1', 1);
g.AddEdge('0', '3', 4);
g.AddEdge('1', '3', 2);
g.AddEdge('1', '2', 9);
g.AddEdge('2', '3', 8);
g.AddEdge('2', '1', 5);
g.AddEdge('2', '0', 3);
g.AddEdge('3', '2', 6);
g.Print();
}
void TestBDFS() {
string a[] = { "张三", "李四", "王五", "赵六", "周七" };
Graph<string, int> g1(a, sizeof(a) / sizeof(string));
g1.AddEdge("张三", "李四", 100);
g1.AddEdge("张三", "王五", 200);
g1.AddEdge("王五", "赵六", 30);
g1.AddEdge("王五", "周七", 30);
g1.Print();
g1.BFS("张三");
g1.DFS("张三");
}
void TestGraphMinTree() {
const char str[] = "abcdefghi";
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);
Graph<char, int> kminTree;
cout << "Kruskal:" << g.Kruskal(kminTree) << endl;
kminTree.Print();
cout << endl;
Graph<char, int> pminTree;
cout << "Prim:" << g.Prim(pminTree, 'a') << endl;
pminTree.Print();
}
void TestGraphDijkstra() {
const char* str = "syztx";
Graph<char, int, INT_MAX, true> g(str, strlen(str));
g.AddEdge('s', 't', 10);
g.AddEdge('s', 'y', 5);
g.AddEdge('y', 't', 3);
g.AddEdge('y', 'x', 9);
g.AddEdge('y', 'z', 2);
g.AddEdge('z', 's', 7);
g.AddEdge('z', 'x', 6);
g.AddEdge('t', 'y', 2);
g.AddEdge('t', 'x', 1);
g.AddEdge('x', 'z', 4);
vector<int> dist;
vector<int> parentPath;
g.Dijkstra('s', dist, parentPath);
g.PrintShortPath('s', dist, parentPath);
}
void TestGraphBellmanFord() {
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', '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', '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.PrintShortPath('s', dist, parentPath);
} else {
cout << "存在负权回路" << endl;
}
}
void TestFloydWarShall() {
const char* str = "12345";
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.PrintShortPath(str[i], vvDist[i], vvParentPath[i]);
cout << endl;
}
}
}
namespace link_table {
template<class W>
struct Edge {
//int _srci;
int _dsti; //目标点的下标
W _w; //权值
Edge<W>* _next;
Edge(int dsti, const W& w) :_dsti(dsti), _w(w), _next(nullptr) {
}
};
template<class V, class W, bool Direction = false>
class Graph {
typedef Edge<W> Edge;
public:
Graph(const V* a, size_t 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);
}
size_t GetVertexIndex(const V& v) {
auto it = _indexMap.find(v);
if (it != _indexMap.end()) {
return it->second;
} else {
//assert(false);
throw invalid_argument("顶点不存在");
return -1;
}
}
void AddEdge(const V& src, const V& dst, const W& w) {
size_t srci = GetVertexIndex(src);
size_t dsti = GetVertexIndex(dst);
Edge* eg = new Edge(dsti, w);
eg->_next = _tables[srci];
_tables[srci] = eg;
if (Direction == false) {
Edge* eg = new Edge(srci, w);
eg->_next = _tables[dsti];
_tables[dsti] = 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 << "]->";
Edge* cur = _tables[i];
while (cur) {
cout << "[" << _vertexs[cur->_dsti] << ":" << cur->_dsti << ":" << cur->_w << "]->";
cur = cur->_next;
}
cout << "nullptr" << endl;
}
}
private:
vector<V> _vertexs; //顶点集合
map<V, int> _indexMap; //顶点映射下标
vector<Edge*> _tables; //邻接表
};
void TestGraph2() {
string a[] = { "张三", "李四", "王五", "赵六" };
//Graph<string, int, true> g1(a, 4);
Graph<string, int> g1(a, 4);
g1.AddEdge("张三", "李四", 100);
g1.AddEdge("张三", "王五", 200);
g1.AddEdge("王五", "赵六", 30);
g1.Print();
}
}
#include<iostream>
using namespace std;
#include"UnionFindSet.h"
#include"Graph.h"
int main() {
//TestUoionFindSet();
//matrix::TestGraph1();
//matrix::TestBDFS();
//matrix::TestGraphMinTree();
//matrix::TestGraphDijkstra();
//matrix::TestGraphBellmanFord();
matrix::TestFloydWarShall();
//link_table::TestGraph2();
return 0;
}

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online