• 高阶数据结构学习之图


    引入

    树是一种特殊(无联通)的图
    图不一定是树
    树关注的节点(顶点)中存的值
    图关注的是顶点及边(边可以代表两个顶点之间的关系)
    图分为有向(类似单向链表)和和无向(类似双向链表)

    图的存储结构

    邻接矩阵

    表示两个顶点的关系
    在这里插入图片描述
    无向图是一个对称矩阵

    附带权值
    在这里插入图片描述

    邻接矩阵优势:
    1.邻接矩阵存储方式非常适合稠密图
    2.O(1)的判断俩个顶点的连接关系,并取到权值

    缺点:
    1.稀疏图
    2.(相对而言)不适合查找一个顶点连接所有边,O(N);

    邻接表

    类似哈希表
    在这里插入图片描述

    优点:
    1.适合存储稀疏图
    2.适合查找一个顶点连接出去的边
    缺点:
    1.不适合确定两个顶点是否相连及权值

    在这里插入图片描述
    一般不需要存储入边表

    总结:
    邻接矩阵和邻接表属于相辅相成,各有优缺点的互补结构

    概念

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

    有向图和无向图:在有向图中,顶点对是有序的,顶点对称为顶点x到顶点y的一条边(弧),是两条不同的边,比如下图G3和G4为有向图。在无向图中,顶点对(x, y)是无序的,顶点对(x,y)称为顶点x和顶点y相关联的一条边,这条边没有特定方向,(x, y)和(y,x)是同一条边,

    完全图:在有n个顶点的无向图中,若有n * (n-1)/2条边,即任意两个顶点之间有且仅有一条边,则称此图为无向完全图,比如上图G1;在n个顶点的有向图中,若有n * (n-1)条边,即任意两个顶点之间有且仅有方向相反的边,则称此图为有向完全图

    邻接顶点:在无向图中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为终点的有向边的条数,记作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条边用最少的边将其连接起来

    代码实现

    邻接矩阵

    //邻接矩阵
    namespace matrix
    {
    
    
    	//V:顶点 W:权值 Direction:有无向
    	template<class V, class W, W MAX_W = INT_MAX, bool Direction = false>
    	class Graph
    	{
    	public:
    		//图的创建
    		//1.IO输入--不方便测试,oj中更适合
    		//2.图结构关系写到文件,读取文件
    		//3.手动添加边
    		Graph(const V* vertexs, size_t n)
    		{
    			_vertexs.reserve(n);
    			for (size_t i = 0; i < n; ++i)
    			{
    				_vertexs.push_back(vertexs[i]);
    				_indexmap[vertexs[i]] = i;
    			}
    
    			_matrix.resize(n);
    			for (auto& e : _matrix)
    			{
    				e.resize(n, MAX_W);
    			}
    
    		}
    
    		//寻找顶点下标
    		size_t GetVertexIndex(const V& v)
    		{
    			auto it = _indexmap.find(v);
    			if (it != _indexmap.end())
    			{
    				return it->second;
    			}
    			else {
    				throw invalid_argument("顶点不存在");
    
    				return -1;
    			}
    		}
    
    		//添加边
    		//src dst顶点 w权值
    		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 (int i = 0; i < _vertexs.size(); ++i)
    			{
    				cout << "[" << i << "]->" << _vertexs[i] << endl;
    			}
    			cout << endl;
    
    			//矩阵
    			cout << "  ";
    			for (size_t i = 0; i < _vertexs.size(); ++i)
    			{
    				cout << i << " ";
    			}
    			cout << endl;
    			for (size_t i = 0; i < _matrix.size(); ++i)
    			{
    				cout << i << " ";
    				for (size_t j = 0; j < _matrix[i].size(); ++j)
    				{
    					if (_matrix[i][j] != MAX_W)
    						cout << _matrix[i][j] << " ";
    					else
    						cout << "#" << " ";
    				}
    				cout << endl;
    			}
    			cout << endl;
    		}
    
    
    	private:
    		vector<V> _vertexs;//顶点集合
    		map<V, int> _indexmap;//顶点映射下标
    		vector<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();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114

    邻接表

    
    //邻接表-出边表
    namespace link_table
    {
    	template<class W>
    	struct Edge
    	{
    		int _dsti;//目标点下标
    		W _w;	  //权值
    		Edge<W>* _next;
    
    		Edge(int dsti,const W w)
    			:_dsti(dsti)
    			,_w(w)
    			,_next(nullptr)
    		{}
    	};
    
    
    	//V:顶点 W:权值 Direction:有无向
    	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 {
    				throw invalid_argument("顶点不存在");
    
    				return -1;
    			}
    		}
    
    		//添加边
    		//src dst顶点 w权值
    		void AddEdge(const V& src, const V& dst, const W& w)
    		{
    			size_t srci = GetVertexIndex(src);
    			size_t dsti = GetVertexIndex(dst);
    
    			//a->b
    			Edge *eg = new Edge(dsti,w);
    			eg->_next = _tables[srci];
    			_tables[srci] = eg;
    
    			//b->a
    			if (Direction == false)
    			{
    				Edge* eg = new Edge(srci, w);
    				eg->_next = _tables[dsti];
    				_tables[dsti] = eg;
    			}
    		}
    
    
    		void Print()
    		{
    			for (int i = 0; i < _vertexs.size(); ++i)
    			{
    				cout << "[" << i << "]->" << _vertexs[i] << endl;
    			}
    			cout << endl;
    
    			for (int 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 TestGraph()
    	{
    		string a[] = { "张三", "李四", "王五", "赵六" };
    		Graph<string, int> g1(a, 4);
    		g1.AddEdge("张三", "李四", 100);
    		g1.AddEdge("张三", "王五", 200);
    		g1.AddEdge("王五", "赵六", 30);
    		g1.Print();
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    图的遍历

    针对的是图的顶点

    广度优先遍历bfs

    在这里插入图片描述

    进行测试

    在这里插入图片描述

    		void BFS(const V& src)
    		{
    			int srci = GetVertexIndex(src);
    			//队列和标记数组
    
    			queue<int> q;
    			vector<bool> visited(_vertexs.size(), false);
    
    			q.push(srci);
    			visited[srci] = true;
    
    			while (!q.empty())
    			{
    				int front = q.front();
    				q.pop();
    				cout << front << ":" << _vertexs[front] << endl;;
    				for (size_t i = 0; i < _vertexs.size(); ++i)
    				{
    					if (visited[i] == false && _matrix[front][i] != MAX_W)
    					{
    						visited[i] = true;
    						q.push(i);
    					}
    				}
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    	void Test()
    	{
    		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("张三");
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    深度优先遍历dfs

    在这里插入图片描述

    进行测试

    在这里插入图片描述

    		void _DFS(int srci, vector<bool> visited)
    		{
    			cout << srci << ":" << _vertexs[srci] << endl;
    			visited[srci] = true;
    
    			for (size_t i = 0; i < visited.size(); i++)
    			{
    				if (_matrix[srci][i] != MAX_W && visited[i] == false)
    					_DFS(i, visited);
    			}
    		}
    		void DFS(const V& src) 
    		{
    			vector<bool> visited(_vertexs.size(), false);
    			_DFS(GetVertexIndex(src), visited);
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    	void TestGraphDBFS()
    	{
    		//为了使得测试更加明显,将李四和王五的位置进行了调整
    		string a[] = { "张三", "王五", "李四", "赵六", "周七" };
    		Graph<string, int> g1(a, sizeof(a) / sizeof(string));
    		g1.AddEdge("张三", "王五", 200);
    		g1.AddEdge("张三", "李四", 100);
    		g1.AddEdge("王五", "赵六", 30);
    		g1.AddEdge("王五", "周七", 30);
    		g1.Print();
    
    		cout << "BFS" << endl;
    		g1.BFS("张三");
    
    		cout << "DFS" << endl;
    		g1.DFS("张三");
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    矩阵不适合走深度和广度
    原因:两个点是否相连不是很容易确定

    最小生成树

    引入
    深度和广度遍历节点的时候
    如果给的图不是连通图,那么以某个点为起点,就不能将其遍历完成,

    概念回顾

    (重要)连通图:在无向图中,若从顶点v1到顶点v2有路径,则称顶点v1与顶点v2是连通的。如果图中任意一对顶点都是连通的,则称此图为连通图。

    (重要)生成树:在无向图中,一个连通图的最小连通子图称作该图的生成树。有n个顶点的连通图的生成树有n个顶点和n-1条边用最少的边将其连接起来

    概念

    构成生成树的这些边加起来权值是最小的

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

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

    构造最小生成树的方法:Kruskal算法和Prim算法。这两个算法都采用了逐步求解的贪心策略。
    贪心算法:是指在问题求解时,总是做出当前看起来最好的选择。也就是说贪心算法做出的不是整体
    最优的的选择,而是某种意义上的局部最优解。贪心算法不是对所有的问题都能得到整体最优解

    Kruskal算法–克鲁斯卡尔算法

    在这里插入图片描述
    在这里插入图片描述
    这样也是最终结果,即:最小生成树不唯一
    判环-并查集

    		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, MAX_W);
    			}
    
    			priority_queue<Edge,vector<Edge>,greater<Edge>> minq;
    			for (int i = 0; i < n; i++)
    			{
    				for (int j = 0; j < n; j++)
    				{
    					if (i < j && _matrix[i][j] != MAX_W)
    					{
    						minq.push(Edge(i, j, _matrix[i][j]));
    					}
    				}
    			}
    
    			int size = 0;
    			W totalW = W();
    			//选出n-1条边
    			UnionFindSet ufs(n);
    			while (!minq.empty())
    			{
    				Edge Min = minq.top();
    				minq.pop();
    
    				if (!ufs.InSet(Min._srci, Min._dsti))
    				{
    					//cout << _vertexs[Min._srci] << "-" << _vertexs[Min._dsti] <<
    						":" << _matrix[Min._srci][Min._dsti] << 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] <<
    						":" << _matrix[Min._srci][Min._dsti] << endl;
    				}
    			}
    			if (size == n - 1)
    			{
    				return totalW;
    			}
    			else {
    				return W();
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    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]));
    				}
    			}
    
    			size_t i = 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] << \
    						":" << _matrix[min._srci][min._dsti] << endl;
    
    				}
    				else
    				{
    					minTree._AddEdge(min._srci, min._dsti, min._w);
    					X[min._dsti] = true;
    					Y[min._dsti] = false;
    					++i;
    					totalW += min._w;
    					if (i == n)
    						break;
    
    					cout << _vertexs[min._srci] << "-" << _vertexs[min._dsti] << \
    						":" << _matrix[min._srci][min._dsti] << endl;
    
    					for (size_t i = 0; i < n; ++i)
    					{
    						if (_matrix[min._dsti][i] != MAX_W && X[i]==false)//X.count(i)统计X中i的个数
    						{
    							minq.push(Edge(min._dsti, i, _matrix[min._dsti][i]));
    						}
    					}
    				}
    				
    			}
    			if (i == n - 1)
    			{
    				return totalW;
    			}
    			else {
    				return W();
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    最短路径

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

    单源最短路径–Dijkstra算法–迪克斯特拉算法

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

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

    在这里插入图片描述
    个人思路:
    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述

    时间复杂度:O(N^2)
    空间复杂度:O(N)

    代码

    		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;
    				}
    			}
    		}
    
    		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;
    				// 松弛更新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;
    					}
    				}
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    void TestGraphDijkstra()
    	{
    		//const char* str = "syztx";
    		//Graph 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 dist;
    		//vector parentPath;
    		//g.Dijkstra('s', dist, parentPath);
    		//g.PrintShortPath('s', dist, parentPath);
    
    		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.PrintShortPath('s', dist, parentPath);
    
    		//s->y->5
    		//s->t->10
    		//s->y->x->8
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    单源最短路径–Bellman-Ford算法–贝尔曼福特算法

    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 n = _vertexs.size();
    			size_t srci = GetVertexIndex(src);
    
    			// vector dist,记录srci-其他顶点最短路径权值数组
    			dist.resize(n, MAX_W);
    			// vector pPath 记录srci-其他顶点最短路径父顶点数组
    			pPath.resize(n, -1);
    			// 先更新srci->srci为缺省值
    			dist[srci] = W();
    
    			//cout << "更新边:i->j" << endl;
    
    			// 总体最多更新n轮
    			for (size_t k = 0; k < n; ++k)
    			{
    				// i->j 更新松弛
    				bool update = false;
    				cout << "更新第:" << k << "轮" << endl;
    				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])
    						{
    							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 (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;
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    	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))
    		{
    			cout << endl;
    			g.PrintShortPath('s', dist, parentPath);
    		}
    		else
    		{
    			cout << "存在负权回路" << endl;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    		// 微调图结构,带有负权回路的测试
    		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;
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    多源最短路径–Floyd-Warshall算法-弗洛伊德算法

    图中任意两点之间的最短路径问题

    代码

    		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] = W();
    					}
    				}
    			}
    
    			// 最短路径的更新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];
    							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)
    							printf("%3c", '*');
    						else
    							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)
    						printf("%3d", vvpPath[i][j]);
    					cout << endl;
    				}
    				cout << "=================================" << endl;
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    	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;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Redis 的大 Key 对持久化有什么影响?
    Gradle在Androidstudio中下载超时提示Download info Connect timed out
    Qt入门(八)——Qt打包(将Qt文件可以在别的Windows系统下运行)
    curl: (56) Recv failure: Connection reset by peer
    【大厂面试必备系列】滑动窗口协议
    6.1 - 6.2 公钥密码学简介
    iTOP-RK3399开发板驱动模块传数组
    C#:如何查看.net core版本?
    Unity UI 完全解决方案
    为什么字节大量用GO而不是Java?
  • 原文地址:https://blog.csdn.net/sakeww/article/details/126449258