【高阶数据结构】图

1. 图的基本概念

是由顶点集合顶点间的关系组成的一种数据结构: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条边

2. 图的存储结构

因为图中既有节点,又有边(节点与节点之间的关系),因此,在图的存储中,只需要保存:节点和边关系即可。节点保存比较简单,只需要一段连续空间即可,那边关系该怎么保存呢?

2.1 邻接矩阵

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

在这里插入图片描述

注意:

  1. 无向图的邻接矩阵是对称的,第i行(列)元素之和,就是顶点i的度。有向图的邻接矩阵则不一定是对称的,第i行(列)元素之后就是顶点i 的出(入)度。

  2. 如果边带有权值,并且两个节点之间是连通的,上图中的边的关系就用权值代替,如果两个顶点不通,则使用无穷大代替

在这里插入图片描述

  1. 邻接矩阵存储图的特点:

    • 邻接矩阵存储方式非常适合稠密图

    • O(1)的时间复杂度判断两个顶点的连接关系, 并取到权值

    • 相对而言,不适合查找一个顶点连接所有边(O(n))

(1) 实现
// 邻接矩阵
namespace matrix
{
	// V: 顶点  W: weight权值  Direction表示图是否有向
	template<class V, class W, W MAX_W=INT_MAX, bool Direction=false>  
	class Graph
	{
		typedef Graph< V, W, MAX_W, Direction> Self;
	public:

		Graph() = default;

		// 图的创建
		// 1. IO输入 --- 不方便测试, oj中更适合
		// 2. 图结构关系写到文件, 读取文件
		// 3. 手动添加边
		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);   // MAX_W 作为不存在边的标识值
			}
		}

		// 查找顶点的下标
		size_t GetVertexIndex(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 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 < _vertexs.size(); ++i)
			{
				cout << "[" << i << "]" << "->" << _vertexs[i] << endl;
			}
			cout << endl;

			// 矩阵(横下标)
			cout << "  ";
			for (size_t i = 0; i < _vertexs.size(); ++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)
					{
						printf("%4c", '*');
					}
					else
					{
						printf("%4d", _matrix[i][j]);
					}
				}
				cout << endl;
			}
			cout << endl;
		}

	private:
		std::vector<V> _vertexs;				// 顶点集合
		std::map<V, int> _indexMap;				// 顶点映射下标
		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.2 邻接表

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

(1) 无向图邻接表存储

在这里插入图片描述

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

(2) 有向图邻接表存储

在这里插入图片描述

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

邻接表存储图的特点:

  • 邻接矩阵存储方式非常适合稀疏图

  • 适合查找一个顶点连接出去的边

  • 不适合确定两个顶点是否相连及权值

(3) 实现
// 邻接表
namespace link_table
{
	template<class W>
	struct Edge
	{
		int _dsti;	     // 目标点下标
		W _w;            // 权值
		Edge<W>* _next;  

		Edge(int dsti,W w)
			:_dsti(dsti)
			,_w(w)
			,_next(nullptr)
		{

		}
	};

	// V: 顶点  W: weight权值
	template<class V, class W, bool Direction = false>
	class Graph
	{
	public:

		typedef Edge<W> Edge;

		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 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 = _tables[srci];
			_tables[srci] = eg;

			// 2->1
			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:
		std::vector<V> _vertexs;				// 顶点集合
		std::map<V, int> _indexMap;				// 顶点映射下标
		std::vector<Edge*> _tables;             // 邻接表
	};

	void TestGraph()
	{
		std::string a[] = { "张三", "李四", "王五", "赵六" };
		Graph<std::string, int> g1(a, 4);
		//Graph<std::string, int, true> g1(a, 4);
		g1.AddEdge("张三", "李四", 100);
		g1.AddEdge("张三", "王五", 200);
		g1.AddEdge("王五", "赵六", 30);
		g1.Print();
	}
}

运行结果:

在这里插入图片描述

3. 图的遍历

给定一个图G和其中任意一个顶点v0,从v0出发,沿着图中各边访问图中的所有顶点,且每个顶点仅被遍历一次。"遍历"即对结点进行某种操作的意思。

3.1 图的广度优先遍历

在这里插入图片描述

在这里插入图片描述

void BFS(const V& src)
{
	size_t srci = GetVertexIndex(src);

	int n = _vertexs.size();
	std::queue<int> q;
	std::vector<bool> visited(n);
	q.push(srci);
	visited[srci] = true;

	while (!q.empty())
	{
		int front = q.front();
		q.pop();
		cout << front << ":" << _vertexs[front] << endl;

		// 把front顶点的邻接顶点入队列
		for (int j = 0; j < n; ++j)
		{
			if (_matrix[front][j] != MAX_W)
			{
				if (visited[j] == false)
				{
					q.push(j);
					visited[j] = true;
				}
			}
		}
	}
	cout << endl;
}

void TestBDFS()
{
	std::string a[] = { "张三", "李四", "王五", "赵六", "周七", "李八" };
	Graph<std::string, int, false> g1(a, sizeof(a) / sizeof(std::string));
	g1.AddEdge("张三", "李四", 100);
	g1.AddEdge("张三", "王五", 200);
	g1.AddEdge("李四", "李八", 500);
	g1.AddEdge("王五", "赵六", 30);
	g1.AddEdge("王五", "周七", 30);
	g1.BFS("张三");
	//g1.BFSlevelsize("张三");
}

运行结果:

在这里插入图片描述

扩展: 查找好友

在这里插入图片描述

void BFSlevelsize(const V& src)
{
	size_t srci = GetVertexIndex(src);

	int n = _vertexs.size();
	std::queue<int> q;
	std::vector<bool> visited(n);
	q.push(srci);
	visited[srci] = true;
	int d = 1;

	while (!q.empty())
	{
		int sz = q.size();
		printf("%s的%d度好友:", src.c_str(), d);

		// 一层一层出
		while (sz--)
		{
			int front = q.front();
			q.pop();

			// 把front顶点的邻接顶点入队列
			for (int j = 0; j < n; ++j)
			{
				if (_matrix[front][j] != MAX_W && visited[j] == false)
				{
					printf("[%d:%s] ", j, _vertexs[j].c_str());
					q.push(j);
					visited[j] = true;
				}
			}
		}
		cout << endl;
		++d;
	}
	cout << endl;
}

运行结果:

在这里插入图片描述

3.2 图的深度优先遍历

在这里插入图片描述

在这里插入图片描述

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

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

void DFS(const V& src)
{
	int srci = GetVertexIndex(src);
	std::vector<bool> visited(_vertexs.size());
	_DFS(srci, visited);
}

void TestBDFS()
{
	std::string a[] = { "张三", "李四", "王五", "赵六", "周七", "李八" };
	Graph<std::string, int, false> g1(a, sizeof(a) / sizeof(std::string));
	g1.AddEdge("张三", "李四", 100);
	g1.AddEdge("张三", "王五", 200);
	g1.AddEdge("李四", "李八", 500);
	g1.AddEdge("王五", "赵六", 30);
	g1.AddEdge("王五", "周七", 30);
	g1.DFS("张三");
}

运行结果:

在这里插入图片描述

4. 最小生成树

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

若连通图由n个顶点组成,则其生成树必含n个顶点和n-1条边。因此构造最小生成树的准则有三条:

  1. 只能使用图中的边来构造最小生成树
  2. 只能使用恰好n-1条边来连接图中的n个顶点
  3. 选用的n-1条边不能构成回路

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

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

4.1 Kruskal算法

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

在这里插入图片描述

W Kruskal(Self& minTree)
{
	int n = _vertexs.size();
	minTree._vertexs = _vertexs;
	minTree._indexMap = _indexMap;
	minTree._matrix.resize(n);

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

	std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> minque;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if (i < j && _matrix[i][j] != MAX_W)
			{
				minque.push(Edge(i, j, _matrix[i][j]));
			}
		}
	}

	// 贪心策略: 从最小的边开始选
	int size = 0;
	W totalW = W();
	yj::UnionFindSet ufs(n);

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

		// 边不在一个集合, 说明不会构成环, 则添加到最小生成树
		if (ufs.FindRoot(min._srci) != ufs.FindRoot(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;
		}
	}

	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('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();
}

运行结果:

在这里插入图片描述

4.2 Prim算法

在这里插入图片描述

具体实现方法:

  1. 用vector定义两个集合,分别表示以选择的边和未选择的边
  2. 定义一个优先级队列,把当前传入顶点srci连接的边入队列
  3. 队列不为空的前提下,选择堆顶元素(当前最小元素)来加入最小生成树,标记两个集合,同时把该元素为顶点的连接边入队列。

判环:

当前最小的目标点也在X集合, 则构成环

在这里插入图片描述

W Prim(Self& minTree, const V& src)
{
	size_t srci = GetVertexIndex(src);
	int n = _vertexs.size();
	minTree._vertexs = _vertexs;
	minTree._indexMap = _indexMap;
	minTree._matrix.resize(n);

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

	// 两个集合
	std::vector<bool> X(n, false);
	std::vector<bool> Y(n, true);
	X[srci] = true;                 // 当前传入集合中的顶点
	Y[srci] = false;                // 除传入顶点以外的顶点

	// X->Y集合中选出最小的边
	std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> minque;
	for (int i = 0; i < n; ++i)
	{
		// 把srci连接的边入队列
		if (_matrix[srci][i] != MAX_W)
		{
			minque.push(Edge(srci, i, _matrix[srci][i]));
		}
	}

	cout << "Prim开始选边" << endl;
	int size = 0;
	W totalW = W();
	while (!minque.empty())
	{
		Edge min = minque.top();
		minque.pop();

		// 最小的目标点也在X集合, 则构成环
		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 (int i = 0; i < n; ++i)
			{
				if (_matrix[min._dsti][i] != MAX_W && Y[i])
				{
					minque.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
				}
			}
		}
	}

	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('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();
	cout << endl;
}

运行结果:

在这里插入图片描述

以str[]各个顶点来构建最小生成树

在这里插入图片描述

5. 最短路径

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

5.1单源最短路径–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算法存在的问题是不支持图中带负权路径,如果带有负权路径,则可能会找不到一些路径的最短路径。

过程图:

在这里插入图片描述

void Dijkstra(const V& src, std::vector<W>& dist, std::vector<int>& pPath)
{
	size_t srci = GetVertexIndex(src);
	int n = _vertexs.size();
      
	dist.resize(n, MAX_W);   // dist: 存储源点到其他顶点的最短路径  
	pPath.resize(n, -1);     // pPath: 存储路径前一个顶点(父顶点)下标

	dist[srci] = 0;
	pPath[srci] = srci;

	// 已确定顶点的下标
	std::vector<bool> S(n, false);

	for (int j = 0; j < n; ++j)   // n个节点更新n次
	{
		// 选最短路径顶点且不在S更新其他路径

		int u = 0;      // 起点到该节点代价最小的节点u
		W min = MAX_W;
		for (int i = 0; i < n; ++i)
		{
			if (S[i] == false && dist[i] < min)
			{
				u = i;
				min = dist[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 &&
				dist[u] + _matrix[u][v] < dist[v])
			{
				dist[v] = dist[u] + _matrix[u][v];
				pPath[v] = u;
			}
		}
	}
}
// 打印最短路径的逻辑算法
void PrintShortPath(const V& src, std::vector<W>& dist, std::vector<int>& pPath)
{
	size_t srci = GetVertexIndex(src);
	int n = _vertexs.size();

	for (size_t i = 0; i < n; ++i)
	{
		if (i != srci)
		{
			// 找出i顶点的路径
			std::vector<int> path;
			size_t parenti = i;
			while (parenti != srci)
			{
				path.push_back(parenti);
				parenti = pPath[parenti];
			}
			path.push_back(srci);
			std::reverse(path.begin(), path.end());

			for (auto index : path)
			{
				cout << _vertexs[index] << "->";
			}
			cout << dist[i] << endl;
		}
	}
}

正常测试用例:

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);

	std::vector<int> dist;
	std::vector<int> parentPath;
	g.Dijkstra('s', dist, parentPath);
	g.PrintShortPath('s', dist, parentPath);
}

在这里插入图片描述

带有负权的路径:

void TestGraphDijkstra()
{
	// 图中带有负权路径时,贪心策略则失效了。
	// 测试结果可以看到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);
	std::vector<int> dist;
	std::vector<int> parentPath;
	g.Dijkstra('s', dist, parentPath);
	g.PrintShortPath('s', dist, parentPath);
}

测试用例中最短路径无法更新出来:

在这里插入图片描述

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

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

bool BellmanFord(const V& src, std::vector<W>& dist, std::vector<int>& pPath)
{
	size_t srci = GetVertexIndex(src);
	int n = _vertexs.size();
	dist.resize(n, MAX_W);
	pPath.resize(n, -1);

	// 先更新srci->srci为缺省值
	dist[srci] = W();

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

		// 如果这轮次中没有更新出更短路径, 那么后续轮次就不需要再走了
		if (update == false)
		{
			break;
		}

		for (int i = 0; i < n; ++i)
		{
			for (int 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('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);
	std::vector<int> dist;
	std::vector<int> pPath;
	g.BellmanFord('s', dist, pPath);
	g.PrintShortPath('s', dist, pPath);

	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);
	std::vector<int> dist;
	std::vector<int> pPath;
	if (g.BellmanFord('s', dist, pPath))
		g.PrintShortPath('s', dist, pPath);
	else
		cout << "带负权回路" << endl;
}

在这里插入图片描述

检测是否带有负权回路:

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);
	std::vector<int> dist;
	std::vector<int> pPath;
	if (g.BellmanFord('s', dist, pPath))
		g.PrintShortPath('s', dist, pPath);
	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是从i到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>>& vvDist, std::vector<std::vector<int>>& vvpPath)
{
	int 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] = W();
			}
		}
	}

	// abcdef  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 (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];

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

					vvpPath[i][j] = vvpPath[k][j];
				}
			}
		}

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

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

在这里插入图片描述

6. 图整体代码

#pragma once
#include<iostream>
#include<vector>
#include<stdexcept>
#include<map>
#include<string>
#include<cstdio>
#include<queue>
#include<functional>
#include"UnionFindSet.h"
using std::cout;
using std::endl;

// 邻接矩阵
namespace matrix
{
	// V: 顶点  W: weight权值
	template<class V, class W, W MAX_W = INT_MAX, bool Direction = false>  // Direction表示图是否有向
	class Graph
	{
		typedef Graph< V, W, MAX_W, Direction> Self;

	public:

		Graph() = default;

		// 图的创建
		// 1. IO输入 --- 不方便测试, oj中更适合
		// 2. 图结构关系写到文件, 读取文件
		// 3. 手动添加边
		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);   // MAX_W 作为不存在边的标识值
			}
		}

		// 查找顶点的下标
		size_t GetVertexIndex(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(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 < _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", _matrix[i][j]);
					}
				}
				cout << endl;
			}
			cout << endl;
		}

		void BFS(const V& src)
		{
			size_t srci = GetVertexIndex(src);

			int n = _vertexs.size();
			std::queue<int> q;
			std::vector<bool> visited(n);
			q.push(srci);
			visited[srci] = true;

			while (!q.empty())
			{
				int front = q.front();
				q.pop();
				cout << front << ":" << _vertexs[front] << endl;

				// 把front顶点的邻接顶点入队列
				for (int j = 0; j < n; ++j)
				{
					if (_matrix[front][j] != MAX_W)
					{
						if (visited[j] == false)
						{
							q.push(j);
							visited[j] = true;
						}
					}
				}
			}
			cout << endl;
		}

		void BFSlevelsize(const V& src)
		{
			size_t srci = GetVertexIndex(src);

			int n = _vertexs.size();
			std::queue<int> q;
			std::vector<bool> visited(n);
			q.push(srci);
			visited[srci] = true;
			int d = 1;

			while (!q.empty())
			{
				int sz = q.size();
				printf("%s的%d度好友:", src.c_str(), d);

				// 一层一层出
				while (sz--)
				{
					int front = q.front();
					q.pop();
					//cout << front << ":" << _vertexs[front] << endl;

					// 把front顶点的邻接顶点入队列
					for (int j = 0; j < n; ++j)
					{
						if (_matrix[front][j] != MAX_W && visited[j] == false)
						{
							printf("[%d:%s] ", j, _vertexs[j].c_str());
							q.push(j);
							visited[j] = true;
						}
					}
				}
				cout << endl;
				++d;
			}
			cout << endl;
		}

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

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

		void DFS(const V& src)
		{
			int srci = GetVertexIndex(src);
			std::vector<bool> visited(_vertexs.size());
			_DFS(srci, visited);
		}

		struct Edge
		{
			size_t _srci;
			size_t _dsti;
			W _w;

			Edge(size_t srci, size_t dsti, W w)
				:_srci(srci)
				, _dsti(dsti)
				, _w(w)
			{

			}

			bool operator>(const Edge& e)const
			{
				return _w > e._w;
			}
		};

		W Kruskal(Self& minTree)
		{
			int n = _vertexs.size();
			minTree._vertexs = _vertexs;
			minTree._indexMap = _indexMap;
			minTree._matrix.resize(n);

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

			std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> minque;
			for (int i = 0; i < n; ++i)
			{
				for (int j = 0; j < n; ++j)
				{
					if (i < j && _matrix[i][j] != MAX_W)
					{
						minque.push(Edge(i, j, _matrix[i][j]));
					}
				}
			}

			// 贪心策略: 从最小的边开始选
			int size = 0;
			W totalW = W();
			yj::UnionFindSet ufs(n);

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

				// 边不在一个集合, 说明不会构成环, 则添加到最小生成树
				if (ufs.FindRoot(min._srci) != ufs.FindRoot(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;
				}
			}

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

		W Prim(Self& minTree, const V& src)
		{
			size_t srci = GetVertexIndex(src);
			int n = _vertexs.size();
			minTree._vertexs = _vertexs;
			minTree._indexMap = _indexMap;
			minTree._matrix.resize(n);

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

			// 两个集合
			std::vector<bool> X(n, false);
			std::vector<bool> Y(n, true);
			X[srci] = true;                 // 当前传入集合中的顶点
			Y[srci] = false;                // 除传入顶点以外的顶点


			// X->Y集合中选出最小的边
			std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> minque;
			for (int i = 0; i < n; ++i)
			{
				// 把srci连接的边入队列
				if (_matrix[srci][i] != MAX_W)
				{
					minque.push(Edge(srci, i, _matrix[srci][i]));
				}
			}

			cout << "Prim开始选边" << endl;
			int size = 0;
			W totalW = W();
			while (!minque.empty())
			{
				Edge min = minque.top();
				minque.pop();

				// 最小的目标点也在X集合, 则构成环
				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 (int i = 0; i < n; ++i)
					{
						if (_matrix[min._dsti][i] != MAX_W && Y[i])
						{
							minque.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
						}
					}
				}
			}

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

		// dist: 存储源点到其他顶点的最短路径    pPath: 存储路径前一个顶点下标
		void Dijkstra(const V& src, std::vector<W>& dist, std::vector<int>& pPath)
		{
			size_t srci = GetVertexIndex(src);
			int n = _vertexs.size();
			dist.resize(n, MAX_W);
			pPath.resize(n, -1);

			dist[srci] = 0;
			pPath[srci] = srci;

			// 已确定顶点的下标
			std::vector<bool> S(n, false);

			for (int j = 0; j < n; ++j)   // n个节点更新n次
			{
				// 选最短路径顶点且不在S更新其他路径

				int u = 0;      // 起点到该节点代价最小的节点u
				W min = MAX_W;
				for (int i = 0; i < n; ++i)
				{
					if (S[i] == false && dist[i] < min)
					{
						u = i;
						min = dist[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 &&
						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, std::vector<W>& dist, std::vector<int>& pPath)
		{
			size_t srci = GetVertexIndex(src);
			int n = _vertexs.size();
			dist.resize(n, MAX_W);
			pPath.resize(n, -1);

			// 先更新srci->srci为缺省值
			dist[srci] = W();

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

				// 如果这轮次中没有更新出更短路径, 那么后续轮次就不需要再走了
				if (update == false)
				{
					break;
				}

				// 还能更新就是带负权回路
				for (int i = 0; i < n; ++i)
				{
					for (int j = 0; j < n; ++j)
					{
						// 检查有没有负权回路
						if (_matrix[i][j] != MAX_W && dist[i] + _matrix[i][j] < dist[j])
						{
							return false;
						}
					}
				}
			}

			return true;
		}


		void FloydWarShall(std::vector<std::vector<W>>& vvDist, std::vector<std::vector<int>>& vvpPath)
		{
			int 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] = W();
					}
				}
			}

			// abcdef  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 (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];

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

							vvpPath[i][j] = vvpPath[k][j];
						}
					}
				}

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

				for (size_t i = 0; i < n; ++i)
				{
					for (size_t j = 0; j < n; ++j)
					{
						//cout << vvParentPath[i][j] << " ";
						printf("%3d", vvpPath[i][j]);
					}
					cout << endl;
				}
				cout << "=================================" << endl;
			}
		}


		void PrintShortPath(const V& src, std::vector<W>& dist, std::vector<int>& pPath)
		{
			size_t srci = GetVertexIndex(src);
			int n = _vertexs.size();

			for (size_t i = 0; i < n; ++i)
			{
				if (i != srci)
				{
					// 找出i顶点的路径
					std::vector<int> path;
					size_t parenti = i;
					while (parenti != srci)
					{
						path.push_back(parenti);
						parenti = pPath[parenti];
					}
					path.push_back(srci);
					std::reverse(path.begin(), path.end());

					for (auto index : path)
					{
						cout << _vertexs[index] << "->";
					}
					cout << dist[i] << endl;
				}
			}
		}


	private:
		std::vector<V> _vertexs;				// 顶点集合
		std::map<V, int> _indexMap;				// 顶点映射下标
		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();
	}

	void TestBDFS()
	{
		std::string a[] = { "张三", "李四", "王五", "赵六", "周七", "李八" };
		Graph<std::string, int, false> g1(a, sizeof(a) / sizeof(std::string));
		g1.AddEdge("张三", "李四", 100);
		g1.AddEdge("张三", "王五", 200);
		g1.AddEdge("李四", "李八", 500);
		g1.AddEdge("王五", "赵六", 30);
		g1.AddEdge("王五", "周七", 30);
		//g1.Print();

		//g1.BFS("张三");
		g1.BFSlevelsize("张三");
		//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();
		cout << endl;

		for (size_t i = 0; i < strlen(str); ++i)
		{
			cout << "Prim:" << g.Prim(pminTree, str[i]) << endl;
		}
	}


	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);

		//std::vector<int> dist;
		//std::vector<int> parentPath;
		//g.Dijkstra('s', dist, parentPath);
		//g.PrintShortPath('s', 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);
		std::vector<int> dist;
		std::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('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);
		std::vector<int> dist;
		std::vector<int> pPath;
		g.BellmanFord('s', dist, pPath);
		g.PrintShortPath('s', dist, pPath);

		const char* str = "syztx";
        Graph<char, int, INT_MAX, true> g1(str, strlen(str));
        g1.AddEdge('s', 't', 6);
        g1.AddEdge('s', 'y', 7);
        g1.AddEdge('y', 'z', 9);
        g1.AddEdge('y', 'x', -3);
        g1.AddEdge('y', 's', 1); // 新增
        g1.AddEdge('z', 's', 2);
        g1.AddEdge('z', 'x', 7);
        g1.AddEdge('t', 'x', 5);
        g1.AddEdge('t', 'y', -8); //更改
        g1.AddEdge('t', 'y', 8);

        g1.AddEdge('t', 'z', -4);
        g1.AddEdge('x', 't', -2);
        std::vector<int> dist;
        std::vector<int> pPath;
        if (g1.BellmanFord('s', dist, pPath))
            g1.PrintShortPath('s', dist, pPath);
        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);
		std::vector<std::vector<int>> vvDist;
		std::vector<std::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 _dsti;	     // 目标点下标
		W _w;            // 权值
		Edge<W>* _next;  

		Edge(int dsti,W w)
			:_dsti(dsti)
			,_w(w)
			,_next(nullptr)
		{

		}
	};


	// V: 顶点  W: weight权值
	template<class V, class W, bool Direction = false>
	class Graph
	{
	public:

		typedef Edge<W> Edge;

		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 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 = _tables[srci];
			_tables[srci] = eg;

			// 2->1
			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:
		std::vector<V> _vertexs;				// 顶点集合
		std::map<V, int> _indexMap;				// 顶点映射下标
		std::vector<Edge*> _tables;             // 邻接表
	};

	void TestGraph()
	{
		std::string a[] = { "张三", "李四", "王五", "赵六" };
		Graph<std::string, int> g1(a, 4);
		//Graph<std::string, int, true> g1(a, 4);
		g1.AddEdge("张三", "李四", 100);
		g1.AddEdge("张三", "王五", 200);
		g1.AddEdge("王五", "赵六", 30);
		g1.Print();
	}
}
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TypeScript是一种静态类型的编程语言,它提供了丰富的类型系统和面向对象的特性,使得开发者可以更好地组织和管理代码。在TypeScript中,高阶数据结构和算法可以通过类和泛型等特性来实现。 高阶数据结构是指那些在基本数据结构的基础上进行扩展或组合得到的数据结构。例如,堆、、树等都可以被视为高阶数据结构。在TypeScript中,我们可以使用类来定义这些高阶数据结构,并通过泛型来指定其内部存储的数据类型。 下面是一个使用TypeScript实现的堆(Heap)数据结构的示例: ```typescript class Heap<T> { private data: T[] = []; public size(): number { return this.data.length; } public isEmpty(): boolean { return this.data.length === 0; } public insert(value: T): void { this.data.push(value); this.siftUp(this.data.length - 1); } public extractMin(): T | null { if (this.isEmpty()) { return null; } const min = this.data[0]; const last = this.data.pop()!; if (!this.isEmpty()) { this.data[0] = last; this.siftDown(0); } return min; } private siftUp(index: number): void { while (index > 0) { const parentIndex = Math.floor((index - 1) / 2); if (this.data[index] >= this.data[parentIndex]) { break; } [this.data[index], this.data[parentIndex]] = [this.data[parentIndex], this.data[index]]; index = parentIndex; } } private siftDown(index: number): void { const size = this.size(); while (index * 2 + 1 < size) { let childIndex = index * 2 + 1; if (childIndex + 1 < size && this.data[childIndex + 1] < this.data[childIndex]) { childIndex++; } if (this.data[index] <= this.data[childIndex]) { break; } [this.data[index], this.data[childIndex]] = [this.data[childIndex], this.data[index]]; index = childIndex; } } } ``` 以上是一个最小堆的实现,使用了数组来存储数据,并提供了插入和提取最小值的操作。堆是一种常见的高阶数据结构,用于解决许多问题,如优先队列和排序等。 通过使用TypeScript,我们可以更加清晰地定义和使用高阶数据结构和算法,并通过类型检查来减少错误和提高代码的可维护性。当然,这只是其中的一个例子,还有许多其他高阶数据结构和算法可以在TypeScript中实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值