最短路径

//最短路径:迪杰斯算法
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;
}

  

原文地址:https://www.cnblogs.com/zhizhi25/p/5895821.html