最短路径

Posted 枝枝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最短路径相关的知识,希望对你有一定的参考价值。

//最短路径:迪杰斯算法
void DJS(vector<vector<int>> &graph,vector<bool> &certain, vector<int> &pre,vector<int> &length,int v)
{
	certain[v] = true;
	pre[v] = v;
	length[v] = 0;
	for (int i = 0; i < graph.size() - 1; i++)
	{
		int min = 255;
		int mark = -1;
		int pre_temp = 0;
		for (int j = 0; j < certain.size(); j++)
		{
			if (certain[j] == true)
			{
				for (int k = 0; k < graph[j].size(); k++)
				{
					if (graph[j][k] != 0 && certain[k] == false && min > (graph[j][k] + length[j]))
					{
						pre_temp = j;
						mark = k;
						min = (graph[j][k] + length[j]);
					}

				}
			}
		}
		if (mark != -1)
		{
			certain[mark] = true;
			pre[mark] = pre_temp;
			length[mark] = min;
		}
		
	}	
}


int main()
{
	int n = 6;
	vector<vector<int>>  graph(n, vector<int>(n));	
	vector<bool> certain(n);
	vector<int> pre(n);
	vector<int> length(n);
	for (int i = 0; i < length.size(); i++)
	{	
		certain[i] = false;
		pre[i] = -1;
		length[i] = 255;

	}
	graph[0] = { 0, 0, 10, 0, 30, 100 };
	graph[1] = { 0, 0, 5, 0, 0, 0 };
	graph[2] = { 0, 0, 0, 50, 0, 0 };
	graph[3] = { 0, 0, 0, 0, 0, 10 };
	graph[4] = { 0, 0, 0, 20, 0, 60 };
	graph[5] = { 0, 0, 0, 0, 0, 0 };
	show_graph(graph);
	cout << endl;
	DJS(graph, certain, pre, length, 0);
	for (int i = 0; i < graph.size(); i++)
	{
		cout << "certain[" << i << "] = " << certain[i] << "    ";
		cout << "pre[" << i << "] = " << pre[i] << "    ";
		cout << "length[" << i << "] = " << length[i] <<endl;
	}	
	system("pause");
	return 0;
}

  

以上是关于最短路径的主要内容,如果未能解决你的问题,请参考以下文章

(王道408考研数据结构)第六章图-第四节3:最短路径之BFS算法(思想代码演示答题规范)

最短路径(Dijkstra算法)

最短路径 深入浅出Dijkstra算法(一)

快看!一条进入公益传播的最短路径就在眼前

最短路径

最短路径问题-Dijkstra(基于图的ADT)