基于Dijkstra算法的最短路径

1. 代码:

#include<iostream>
#include<string>

using namespace std;

struct Dis {
	string path;
	int value;
	bool visit;
	Dis() {
		visit = false;
		value = 0;
		path = "";
	}
};

class Graph {
private:
	int vexnum;   //图的顶点个数
	int edge;     //图的边数
	int **arc;   //邻接矩阵
	Dis * dis;   //记录各个顶点最短路径的信息
public:
	//构造函数
	Graph(int vexnum, int edge);

	//创建图
	void createGraph();

	//求最短路径
	void Dijkstra(int begin);

	//打印最短路径
	void print_path(int);
};


Graph::Graph(int vexnum, int edge) {
	//初始化顶点数和边数
	this->vexnum = vexnum;
	this->edge = edge;
	//为邻接矩阵开辟空间和赋初值
	arc = new int*[this->vexnum];
	dis = new Dis[this->vexnum];
	for (int i = 0; i < this->vexnum; i++) {
		arc[i] = new int[this->vexnum];
		for (int k = 0; k < this->vexnum; k++) {
			//邻接矩阵初始化为无穷大
			arc[i][k] = INT_MAX;
		}
	}
}

void Graph::createGraph() {
	cout << "输入每条边的起点和终点及权重" << endl;
	int start;
	int end;
	int weight;
	int count = 0;
	while (count != this->edge) {
		cin >> start >> end >> weight;
		//对邻接矩阵对应上的点赋值
		arc[start][end] = weight;
		arc[end][start] = weight;
		++count;
	}
}

void Graph::Dijkstra(int begin) {
	//首先初始化我们的dis数组
	int i;
	for (i = 0; i < this->vexnum; i++) {
		//设置当前的路径
		dis[i].path = "v" + to_string(begin - 1) + "-->v" + to_string(i);
		dis[i].value = arc[begin - 1][i];
	}
	//设置起点的到起点的路径为0
	dis[begin - 1].value = 0;
	dis[begin - 1].visit = true;

	int count = 1;
	//计算剩余的顶点的最短路径(剩余this->vexnum-1个顶点)
	while (count != this->vexnum) {
		//temp用于保存当前dis数组中最小的那个下标
		//min记录的当前的最小值
		int temp = 0;
		int min = INT_MAX;
		for (i = 0; i < this->vexnum; i++) {
			if (!dis[i].visit && dis[i].value < min) {
				min = dis[i].value;
				temp = i;
			}
		}

		dis[temp].visit = true;
		++count;
		for (i = 0; i < this->vexnum; i++) {
			//注意这里的条件arc[temp][i]!=INT_MAX必须加,不然会出现溢出,从而造成程序异常
			if (!dis[i].visit && arc[temp][i] != INT_MAX && (dis[temp].value + arc[temp][i]) < dis[i].value) {
				//如果新得到的边可以影响其他为访问的顶点,那就就更新它的最短路径和长度
				dis[i].value = dis[temp].value + arc[temp][i];
				dis[i].path = dis[temp].path + "-->v" + to_string(i);
			}
		}
	}

}

void Graph::print_path(int begin) {
	cout << "图的最短路径为:" << endl;
	for (int i = 0; i != this->vexnum; i++) {
		cout << dis[i].path << "=" << dis[i].value << endl;
	}
}

int main() {
	int vexnum; int edge;
	cout << "输入图的顶点个数和边的条数:" << endl;
	cin >> vexnum >> edge;
	Graph graph(vexnum, edge);
	graph.createGraph();
	graph.Dijkstra(1);
	graph.print_path(1);
	return 0;
}


2. 运行效果:



猜你喜欢

转载自blog.csdn.net/JZJZ73/article/details/80501270
今日推荐