02 图结构

目录

  1. 图的基本概念
  2. 图的存储结构
  3. 图的遍历
  4. 最小生成树
  5. 最短路径问题

1.图的基本概念

图是由顶点集合及顶点间的关系组成的一种数据结构:G=(V,E),其中:
顶点集合V={x | x属于某个数据对象集} 是有穷非空集合
E= {(x,y) | x,y属于V}或者E={<x,y>,x,y属于V && Path(x,y)}是顶点间关系的有穷集合,也叫做边的集合

顶点和边:图中节点称为顶点,第i个顶点记作Vi,两个顶点vi和vj相关联成称作顶点vi和顶点vj之间有一条边,图中的第k条边记作ek,ek=(vi,v)或<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个n-1条边

树是一种特殊(无环连通的)的图,图不一定是树
树关注的节点(顶点)中存的值,图关注的是顶点及边的权值
如果将边的权值看做好友的亲密度,微信、qq等关系是无向图,强社交关系。微博、抖音是有向图,弱社交关系

2. 图的存储结构

因为图中既有节点,又有边,因此,图的存储只需要保存节点和边关系即可,节点只需要一段连续的空间,那么边呢

2.1 邻接矩阵

因为节点与节点之间的关系就是连通与否,即0或者-1,因此邻接矩阵可以用二维数组,先用一个数组将定点保存,然后采用矩阵表示节点和节点的关系

在这里插入图片描述

注意:
1.无向图的邻接矩阵是对称的,第i行(列)元素之和,就是顶点的度,有向图的邻接矩阵则不一定是对称的,第i行(列)元素之后就是顶点i的出(入)度
2.如果边带有权值,并且两个节点之间是连通的,上图中的边的关系就用权值代替。如果不通,则使用无穷大

在这里插入图片描述

3.用领接矩阵存储图的优点可以快速知道两个顶点是否连通,缺陷是如果顶点较多,边比较少时,矩阵存储了大量的0成为系数矩阵,比较浪费空间,并且要求两个节点之间的路径不是很好求

邻接矩阵非常适合稠密图,判断两个顶点关系并取到权值,不适合查找一个顶点连接的所有边O(N)。由于对角线两边是一样的,节省空间也可以只存一半

2.2 邻接矩阵实现

用vector保存顶点,map保存顶点映射的数组下标。边用二维数组表示

template <class V, class W, W MAX_W = INT_MAX, bool Direction = false>
class Graph
{
public:
	// 图的创建
	// 1.io输入,不方便测试
	// 2.图结构关系写到文件, 读取文件
	// 3.手动添加边
	Graph(const V* ary, size_t n)
	{
		_vertex.reserve(n);
		for (int i = 0; i < n; i++)
		{
			_vertex.push_back(ary[i]);
			_map[ary[i]] = i;
		}

		_matrix.resize(n);
		for (int i = 0; i < n; i++)
		{
			_matrix[i].resize(n, MAX_W);
		}
	}

	size_t GetVertexIndex(const V& v)
	{
		auto ret = _map.find(v);
		if (ret != _map.end())
		{
			return ret->second;
		}

		//assert(false);
		throw std::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);

		_matrix[srci][dsti] = w;
		// 无向图
		if (Direction == false)
		{
			_matrix[dsti][srci] = w;
		}

	}

	void Print()
	{
		for (size_t i = 0; i < _vertex.size(); i++)
		{
			std::cout << "[" << i << "]" << "->" << _vertex[i] << std::endl;
		}
		std::cout << std::endl;

		// 打印下标
		std::cout << "  ";
		for (size_t i = 0; i < _matrix.size(); i++)
		{
			//std::cout << i << " ";
			printf("%4d", i);
		}
		std::cout << std::endl;

		// 打印矩阵
		for (size_t i = 0; i < _matrix.size(); i++)
		{
			std::cout << i << " ";
			for (size_t j = 0; j < _matrix[i].size(); j++)
			{
				if (_matrix[i][j] == MAX_W)
				{
					//std::cout << "* ";
					printf("%4c", '*');
				}
				else
				{
					//std::cout << _matrix[i][j] << " ";
					printf("%4d", _matrix[i][j]);
				}
			}
			std::cout << std::endl;
		}

	}

private:
	std::vector<V> _vertex;               // 顶点集合
	std::map<V, int> _map;                // 顶点映射下标
	std::vector<std::vector<W>> _matrix;  // 边的集合
};
void TestGraph()
 {
 Graph<char, int, INT_MAX, 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();
}

2.3 邻接表

邻接表:使用数组表示顶点的集合,使用链表表示边的关系

  1. 无向图邻接表矩阵

在这里插入图片描述
注意:无向图中同一条边在邻接表中出现了两次,如果想知道顶点vi的度,只需要知道顶点vi边链表集合中节点的数目即可

  1. 有向图邻接表存储

在这里插入图片描述
注意:有向图中每条边在邻接表中只出现了一次,与顶点vi对应的邻接表中所含节点的个数,就是该顶点的出度,也称出度表,要得到vi顶点的入度,必须检测其他所有顶点对应的边链表,看有多少边顶点的dst取值是i

有向图适合存储稀疏图,适合查找一个顶点连接出去的边,不适合确定两个顶点是否相连及权值

2.4 邻接表实现

和矩阵一样,保存顶点和对应关系,邻接表的边用一个结构,成员目标顶点,边的值,下一个边的指针连接起来

// 邻接表
template <class W>
struct Edge
{
	//int srci;
	int _dsti;
	W _w;
	struct Edge<W>* _next;

	Edge(int dsti, const W& w)
		:_dsti(dsti),
		 _w(w),
		 _next(nullptr)
	{}
};

template <class V, class W, bool Direction = false>
class LinkTable
{
	typedef struct Edge<W> Edge;
public:
	LinkTable(const V* ary, size_t n)
	{
		_vertex.reserve(n);
		for (int i = 0; i < n; i++)
		{
			_vertex.push_back(ary[i]);
			_map[ary[i]] = i;
		}

		_table.resize(n, nullptr);
	}

	size_t GetVertexIndex(const V& v)
	{
		auto ret = _map.find(v);
		if (ret != _map.end())
		{
			return ret->second;
		}

		//assert(false);
		throw std::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);

		// 1 -> 2
		Edge* eg = new Edge(dsti, w);
		eg->_next = _table[srci];
		_table[srci] = eg;
		// 无向图 2 -> 1
		if (Direction == false)
		{
			Edge* eg = new Edge(srci, w);
			eg->_next = _table[dsti];
			_table[dsti] = eg;
		}

	}

	void Print()
	{
		for (size_t i = 0; i < _vertex.size(); i++)
		{
			std::cout << "[" << i << "]" << "->" << _vertex[i] << std::endl;
		}
		std::cout << std::endl;

		// 打印表
		for (size_t i = 0; i < _table.size(); i++)
		{
			std::cout << _vertex[i] << "[" << i << "]" << "->" ;

			Edge* cur = _table[i];
			while (cur)
			{
				std::cout << _vertex[cur->_dsti] << "[" << cur->_dsti << "]" << cur->_w  << "->";
				cur = cur->_next;
			}

			std::cout << "nullptr" << std::endl;
		}

	}

private:
	std::vector<V> _vertex;               // 顶点集合
	std::map<V, int> _map;                // 顶点映射下标
	std::vector<Edge*> _table;            // 邻接表
};

3. 图的遍历

给定一个图G和其中任意一个顶点v0,从v0出发,沿着图中各边访问投入图中所有顶点,且每个顶点仅被遍历一次,思考怎么遍历

3.1 图的广度优先遍历

在这里插入图片描述

从起点开始,每次遍历相邻的一层所有顶点,所以用一个队列,当顶点出去时,将它所有相邻的边都入队,不断重复,有可能队列中存在已经遍历过的,所以用一个数组记录有没有输出过

 广度优先遍历
//void BFS(const V& src)
//{
//	int srci = GetVertexIndex(src);
//	std::queue<int> que;
//	que.push(srci);

//	// 记录有没有访问过
//	std::vector<bool> visited(_vertex.size(), false);
//	visited[0] = true;

//	while (!que.empty())
//	{
//		int front = que.front();
//		que.pop();
//		std::cout << front << ":" << _vertex[front] << std::endl;
//		for (int i = 0; i < _matrix[front].size(); i++)
//		{
//			if (_matrix[front][i] != MAX_W)
//			{
//				if (visited[i] != true)
//				{
//					que.push(i);
//					visited[i] = true;
//				}
//			}
//		}
//	}

//}

// 广度优先遍历
// 按层打印
void BFS(const V& src)
{
	int srci = GetVertexIndex(src);
	std::queue<int> que;
	que.push(srci);

	// 记录有没有访问过
	std::vector<bool> visited(_vertex.size(), false);
	visited[0] = true;
	int levelsize = 1;

	while (!que.empty())
	{
		for (int i = 0; i < levelsize; i++)
		{
			int front = que.front();
			que.pop();
			std::cout << front << ":" << _vertex[front] << " ";
			for (int i = 0; i < _matrix[front].size(); i++)
			{
				if (_matrix[front][i] != MAX_W)
				{
					if (visited[i] != true)
					{
						que.push(i);
						visited[i] = true;
					}
				}
			}
		}		

		std::cout << std::endl;
		levelsize = que.size();
	}

}

3.2 图的深度优先遍历

在这里插入图片描述

从A点开始,到B一直走到D,直到没有路时,就往回退,退到F点又可以访问H和I,继续往回退,直到所有点都访问过了

深度优先适合递归,从这个点出发一直有可以访问的点就不停往下,直到没有了就返回上一层调用

void _DFS(int srci, std::vector<bool>& visited)
{
	std::cout << srci << ":" << _vertex[srci] << std::endl;
	visited[srci] = true;

	// 找一个srci相邻的没有访问过的点, 去往深度遍历
	for (int i = 0; i < _vertex.size(); i++)
	{
		if (_matrix[srci][i] != MAX_W && visited[i] == false)
		{
			_DFS(i, visited);
		}
	}
}

// 深度优先遍历
void DFS(const V& src)
{
	int srci = GetVertexIndex(src);
	std::vector<bool> visited(_vertex.size(), false);

	_DFS(srci, visited);
}

4. 最小生成树

连通图中的每一棵生成树,都是原图的一个极大无环子图,即:从其中删去任何一条边,生成树就不连通;反之,在其中引入任何一条新边,都会形成一条回路

若连通图由n个顶点组成,则其生成树必包含n个顶点和n-1条边。因此,构造最小生成树的准则有三条:
1.只能使用图中的边来构成
2.只能使用恰好n-1条边来连接图中的n个顶点
3.选用的n-1条边不能构成回路

构成最小生成树的方法:Kruskal算法和Prim算法,都采用了逐步求解的贪心策略

贪心算法:指在问题求解时,总是做出当前看起来最好的选择。也就是说贪心算法做出的不是整体最优的选择,而是局部最优解,不是对所有的问题都能得到整体最优解

4.1 Kruskal算法

任给一个有n个顶点的连通网络N={V,E}
首先构造一个由n个顶点组成,不含任何边的图(V,NULL),其中每个顶点自成一个连通分量。其次不断从E中取出权值最小的一条边,有多条任取其一,若该边的两个顶点来自不同的连通分量,则将此边加入到G中。如此重复,直到所有顶点在同一个连同分量为止

思路:先初始化一个顶点相同的空图,用一个优先级队列保存所有不重复的边,每次从堆中取出权值最小的,如果两个顶点不构成环,就加入到图中。可以用并查集来判断,在同一个集合就会构成环。如果边的数量是n-1,就找到了最小生成树

在这里插入图片描述

W Kruskal(self& min_tree)
{
	size_t n = _vertex.size();

	// 初始化生成树
	min_tree._vertex = _vertex;
	min_tree._map = _map;
	min_tree._matrix.resize(n);
	for (int i = 0; i < n; i++)
	{
		min_tree._matrix[i].resize(n, MAX_W);
	}
	
	std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> que;
	// 初始化堆
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			// 重复边不需要加入
			if (i < j && _matrix[i][j] != MAX_W)
			{
				que.push(Edge(i, j, _matrix[i][j]));
			}
		}
	}

	// 选n-1条边
	int size = 0;
	W total_w = W();
	// 并查集判环
	UnionFindSet set(n);

	while (!que.empty())
	{
		Edge min = que.top();
		que.pop();

		if (!set.InSet(min._srci, min._dsti))
		{			
			std::cout << _vertex[min._srci] << "->" << _vertex[min._dsti] << ":" << min._w << std::endl;
			min_tree._AddEdge(min._srci, min._dsti, min._w);
			set.Union(min._srci, min._dsti);
			total_w += min._w;
			size++;
		}
		else
		{
			std::cout << "构成环:";
			std::cout << _vertex[min._srci] << "->" << _vertex[min._dsti] << ":" << min._w << std::endl;
		}
	}

	if (size == n - 1)
	{
		return total_w;
	}
	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();
 Graph<char, int> pminTree;
 cout << "Prim:" << g.Prim(pminTree, 'a') << endl;
 pminTree.Print();
 }

在这里插入图片描述

4.2 Prim算法

与上面的算法相似,具有的一个性质时集合A中的边总是构成一颗树,这棵树从任意一个的根节点r开始,一直长大直到覆盖V中的所有顶点为止。局部贪心,从顶点V开始,从连接的边的集合中挑中权值最小的连接,将目标点链接的边也加入考虑之中,然后从剩下的边挑出权值最小的加入

在这里插入图片描述
思路:用X和Y两个数组,X初始时空,Y是所有顶点对应的下标。先将起始顶点加入到X中,Y中删去,从这个点相连的边挑出权值最小的,挑出后将目标顶点加入X,Y中删去。用优先级队列保存剩下的所有的边的权重。最后如果选出的数量是n-1,就返回总权值

W Prim(self& min_tree, const V& src)
{
	size_t srci = GetVertexIndex(src);
	size_t n = _vertex.size();

	// 初始化生成树
	min_tree._vertex = _vertex;
	min_tree._map = _map;
	min_tree._matrix.resize(n);
	for (int i = 0; i < n; i++)
	{
		min_tree._matrix[i].resize(n, MAX_W);
	}

	// 初始化两个集合
	/*std::set<int> X;
	std::set<int> Y;
	X.insert(srci);*/

	std::vector<bool> X;
	std::vector<bool> Y;
	X.resize(n, false);
	Y.resize(n, true);
	X[srci] = true;
	Y[srci] = false;

	/*for (size_t i = 0; i < n; i++)
	{
		if (i != srci)
		{
			Y.insert(i);
		}
	}*/

	// 从X->Y集合中连接的边里面选出最小的边
	std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> que;
	// 先把src相邻的边加入
	for (size_t i = 0; i < n; i++)
	{
		if (_matrix[srci][i] != MAX_W)
		{
			que.push(Edge(srci, i, _matrix[srci][i]));
		}
	}

	size_t size = 0;
	W total_w = W();
	while (!que.empty())
	{
		Edge min = que.top();
		que.pop();

		// 最小边的目标点也在X集合,则构成环
		if (X[min._dsti])
		{
			std::cout << "构成环:";
			std::cout << _vertex[min._srci] << "->" << _vertex[min._dsti] << ":" << min._w << std::endl;

		}
		else
		{
			min_tree._AddEdge(min._srci, min._dsti, min._w);
			std::cout << _vertex[min._srci] << "->" << _vertex[min._dsti] << ":" << min._w << std::endl;
			// 更新集合
			/*X.insert(min._dsti);
			Y.erase(min._dsti);*/
			X[min._dsti] = true;
			Y[min._dsti] = false;
			size++;
			total_w += min._w;
		}
		
		// 选完退出
		if (size == n - 1)
		{
			break;
		}

		// dst相邻的边加入
		for (size_t i = 0; i < n; i++)
		{
			if (_matrix[min._dsti][i] != MAX_W && Y[i])
			{
				que.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
			}
		} 
	}

	if (size == n - 1)
	{
		return total_w;
	}
	else
	{
		return W();
	}	
}

在这里插入图片描述

5. 最短路径

最短路径的问题:从在带权有向图G中的某一顶点出发,找出一条通过往另一个顶点的最短路径,最短也就是沿路径各边的权值总和达到最小

5.1 单源最短路径–Dijkstra算法

单源最短路径问题:给定一个图G = ( V , E ) G=(V,E)G=(V,E),求源结点s ∈ V s∈Vs∈V到图中每个结点v ∈ V的最短路径。这个算法适用于解决带权重的有向图上的单源最短路径问题,同时算法要求图中所有权重非负。一般在求解最短路径的时候都是已知一个起点和终点,所以使用Dijkstra算法求解过之后也就得到了所需起点和终点的最短路径

针对一个带权有向图G,将所有节点分为两组S和Q,S是已经确定最短路径的节点集合,在初始时为空(初始时将源节点S放入,到自己的代价是0),Q是其余未确定最短路径的节点集合,每次从Q中找出一个起点到终点代价最小的节点u,将u从Q中移出,并放入S中,对u的每一个相邻节点v进行松弛操作,松弛即对每一个相邻节点v,判断源节点s到节点u的代价与u到v的代价之和是否比原来的s到v的代价更小,若小就更新s到u和u到v的代价之和,否则维持原样。如此一直循环直到集合Q未空,即所有节点都查找过一遍并确定了最短路径,至于一些起点到达不了的及节点在算法循环后其代价仍为初始设定的值,不发生变化,每次都是选择最小路径更新,加入S,是贪心策略

算法存在的问题是不支持图中带负权路径,如果带有负权路径,可能会找不到一些路径的最短路径

在这里插入图片描述

// 顶点个数是N  -> 时间复杂度:O(N^2)空间复杂度:O(N)
void Dijkstra(const V& src, std::vector<W>& dist, std::vector<int>& p_path)
{
	size_t srci = GetVertexIndex(src);
	size_t n = _vertex.size();
	dist.resize(n, MAX_W);
	p_path.resize(n, -1);

	dist[srci] = 0;
	p_path[srci] = srci;

	// 已经确定最短路径的顶点集合
	std::vector<bool> S(n, false);

	for (size_t i = 0; i < n; i++)
	{		
			// 选最短路径顶点且不在S更新其他路径
			int u = 0;
			W min = MAX_W;

			for (size_t j = 0; j < n; j++)
			{
				if (S[j] == false && dist[j] < min)
				{
					u = j;
					min = dist[j];
				}
			}

			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
					&& dist[u] + _matrix[u][v] < dist[v])
				{
					dist[v] = dist[u] + _matrix[u][v];
					p_path[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('x', dist, parentPath);
	g.PrintShortPath('x', dist, parentPath);
	// 图中带有负权路径时,贪心策略则失效了。
   // 测试结果可以看到s->t->y之间的最短路径没更新出来
   /*const char* str = "sytx";
	Graph<char, int, INT_MAX, true> g(str, strlen(str));
	g.AddEdge('s', 't', 10);
	g.AddEdge('s', 'y', 5);
	g.AddEdge('t', 'y', -7);
	g.AddEdge('y', 'x', 3);
	vector<int> dist;
	vector<int> parentPath;
	g.Dijkstra('s', dist, parentPath);
	g.PrinrtShotPath('s', dist, parentPath);*/
}

5.2 单源最短路径–Bellman-Ford算法

Dijkstra不能解决负权图的情况,BellmanFord可以,优点是可以解决有负权边的最短路径,也可以用来判断是否有负权回路。也有明显的缺点,时间复杂度是O(N*E)(N是点数,E是边数),普遍是高于Dijkstra算法O(N²)的,像这里如果我们使用邻接矩阵实现,那么遍历所有的边的数量的时间复杂度就是O(N3),是一种暴力求解更新

在这里插入图片描述

// 时间复杂度:O(N^3) 空间复杂度:O(N)
bool BellmanFord(const V& src, std::vector<W>& dist, std::vector<int>& p_path)
{
	size_t srci = GetVertexIndex(src);
	size_t n = _vertex.size();

	dist.resize(n, MAX_W);
	p_path.resize(n, -1);

	// 初始化
	dist[srci] = W();

	// 总体更新n轮
	for (size_t k = 0; k < n; k++)
	{
		bool update = false;
		// i->j松弛更新
		for (size_t i = 0; i < n; i++)
		{
			for (size_t j = 0; j < n; j++)
			{
				// srci->i + i->j
				if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j])
				{
					//std::cout << _vertex[i] << "->" << _vertex[j] << ":" << _matrix[i][j] << std::endl;
					dist[j] = dist[i] + _matrix[i][j];
					p_path[j] = i;
					update = true;
				}
			}		
		}

		// 如果这个轮次没有更新最短路径, 后续不需要走了
		if (update == false)
		{
			break;
		}
	}

	// 如果还能更新, 就是带负权回路
	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < n; j++)
		{
			// srci->i + i->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('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.PrintShortPath('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.PrintShortPath('s', dist, parentPath);
	}
	else
	{
	  cout << "存在负权回路" << endl;
	}
}

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是从j到k且中间节点属于{1,2,。。。,k-1}取得的一条最短路径。p2是从k到j且中间节点属于{1,2,。。。,k-1}取得的一条最短路径

在这里插入图片描述在这里插入图片描述
即Floyd算法本质是三维动态规划,D[i][j][k]表示从点i到点j只经过0到k个点最短路径,然后建立起转移方程,然后通过空间优化,优化掉最后一维度,变成一个最短路径的迭代算法,最后即得到所以点的最短路。

在这里插入图片描述

void FloydWarshall(std::vector<std::vector<W>>& vv_dist, std::vector<std::vector<int>>& vv_path)
{
	size_t n = _vertex.size();
	vv_dist.resize(n);
	vv_path.resize(n);

	// 初始化权值和路径矩阵
	for (size_t i = 0; i < n; i++)
	{
		vv_dist[i].resize(n, MAX_W);
		vv_path[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)
			{
				vv_dist[i][j] = _matrix[i][j];
				vv_path[i][j] = i;
			}

			if (i == j)
			{
				vv_dist[i][j] = W();
			}
		}
	}

	// ancdef a {} f || b {} c
	// 最短路径的更新 i-> {其他顶点} ->j
	for (size_t k = 0; k < n; k++)
	{
		for (size_t i = 0; i < n; i++)
		{
			for (size_t j = 0; j < n; j++)
			{
				// k 作为的中间点尝试去更新i->j的路径
				if (vv_dist[i][k] != MAX_W && vv_dist[k][j] != MAX_W
					&& vv_dist[i][k] + vv_dist[k][j] < vv_dist[i][j])
				{
					vv_dist[i][j] = vv_dist[i][k] + vv_dist[k][j];

					// 找跟j相连的上一个邻接顶点
					// 如果k->j 直接相连,上一个顶点就是k, vv_path[k][j]存的就是k
				    // 如果k->j 没有直接相连,k->...->x->j, vv_path[k][j]存的就是x
					vv_path[i][j] = vv_path[k][j];
				}
			}
		}
	}

	// 打印权值和路径矩阵观察数据
	for (size_t i = 0; i < n; ++i)
	{
		for (size_t j = 0; j < n; ++j)
		{
			if (vv_dist[i][j] == MAX_W)
			{
				//cout << "*" << " ";
				printf("%3c", '*');
			}
			else
			{
				//cout << vvDist[i][j] << " ";
				printf("%3d", vv_dist[i][j]);
			}
		}
		std::cout << std::endl;
	}
	std::cout << std::endl;

	for (size_t i = 0; i < n; ++i)
	{
		for (size_t j = 0; j < n; ++j)
		{
			//cout << vvParentPath[i][j] << " ";
			printf("%3d", vv_path[i][j]);
		}
		std::cout << std::endl;
	}
	std::cout << "=================================" << std::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;
	}
}

原理及图文大量参考了《算法导论》和《殷人昆 数据结构:用面向对象方法与C++语言描述 (第二版)》的内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值