算法题——迪杰斯特拉实现

图示:

代码:

#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
using namespace std;

vector<vector<int>> buildgraph(vector<vector<int>>&edges,int n) {
	vector<vector<int>> graph(n, vector<int>(n, INT_MAX));
	for (int i = 0; i < edges.size(); i++) {
		int m = edges[i][0], k = edges[i][1], w = edges[i][2];
		graph[m][k] = w;
	}
	return graph;
}

vector<int> dijkstra(vector<vector<int>>& edges,int n) {
	vector<vector<int>> adjacent_matrix = buildgraph(edges, n);
	vector<int> point(n, INT_MAX);
	vector<int> path(n, -1);
	path[0] = 0; point[0] = 0;

	for (int i = 0; i < n; i++) {
		int index = 0, min_w = INT_MAX;
		for (int j = 0; j < n; j++) {
			if (point[j] == -1) continue;
			if (point[j] < min_w) {
				min_w = point[j];
				index = j;
			}
		}

		for (int j = 0; j < n; j++) {
			if (adjacent_matrix[index][j] == INT_MAX)continue;
			int temp = adjacent_matrix[index][j] + point[index];
			if (point[j] > temp) {
				point[j] = temp;
				path[j] = index;
			}
		}
		point[index] = -1;
	}
	return path;
}
int main() {

	vector<vector<int>>edges = { {0,1,9},{0,2,14},{0,3,15},{1,4,24},{2,4,18},{2,5,30},{3,5,20},{3,7,44},{4,5,2},{4,7,19},{5,6,11},{5,7,16},{6,7,6} };
	vector<int> res = dijkstra(edges, 8);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值