【数据结构】Dijkstra求最短路径的图的邻接矩阵的实现

这个早就写好了,但是实验室的网CSDN有时候登不上去。就一直忘记了。现在补上。

其实就算一个贪心算法吧,看了很多资料,然后在自己之前写的邻接矩阵类中写,编译试了一下好像没出什么问题。代码如下,关于邻接矩阵的构造请参考之前的代码。

void Map::Dijkstra(int i)
{
	//访问设置归0 
	cleanVisited();
	//初始化数据结构
	int *dv = new int[VertexNum];
	int *pv = new int[VertexNum];
	for (int i = 0; i < VertexNum; i++)
	{
		dv[i] = MAX_Weight;
		pv[i] = 0;
	}
	dv[i] = 0;
	int current_vertex = i;
	while (notfinished())
	{
		//已经访问了当前点
		visited[current_vertex] = true;
		int ps = dv[current_vertex];
		for (int j = 0; j < VertexNum; j++)
		{
			if (j != current_vertex&&visited[j] == false)
			{
				//算长度
				int ds = ps + Edges[current_vertex][j];
				if (ds < dv[j])
				{
					dv[j] = ds;
					pv[j] = current_vertex;
				}
			}
		}
		int min = MAX_Weight;
		for (int m = 0; m < VertexNum; m++)
		{
			if (visited[m] == false&&min>dv[m])
			{
				min = dv[m];
				current_vertex = m;
			}
		}
	}
}


猜你喜欢

转载自blog.csdn.net/qq_31548387/article/details/78266248