最短路:迪傑斯特拉算法

迪傑斯特拉算法

在這裏插入圖片描述
僞代碼
在這裏插入圖片描述

這裏是引用

#include<queue>
#include<stack>
#include<vector>
#include<string>
#include<iostream>
#include<stdio.h>
using namespace std;
const int LEN = 7;
const int inf = INT_MAX;
int Graph[LEN][LEN] =
{ {-1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, 10, -1, 30, 100},
{-1, -1, -1, 5,  -1, -1, -1},
{-1, -1, -1, -1, 50, -1, -1},
{-1, -1, -1, -1, -1, -1, 10},
{-1, -1, -1, -1, 20, -1, 60},
{-1, -1, -1, -1, -1, -1, -1} };
int crateGraph()
{
	for (int i = 1; i < LEN; i++)
	{
		for (int j = 0; j < LEN; j++)
		{
			if (Graph[i][j] == -1)
				Graph[i][j] = INT_MAX;
			if(i == j)
				Graph[i][j] = 0;
		}
	}
	return 0;
}

int print(void)
{
	for (int i = 1; i < LEN; i++)
	{
		for (int j = 1; j < LEN; j++)
		{
			if(Graph[i][j] != INT_MAX)
				cout << Graph[i][j] << " ";
			else
				cout <<"∞" << " ";
		}
		cout << endl;
	}
	return 0;
}
int Dijkstra(int s)
{

	string path[LEN];
	int dist[LEN] = {0};
	int visit[LEN] = {0};
	 
	visit[s] = 1;
	
	for (int i = 1; i < LEN; i++)
	{
		dist[i] = Graph[s][i];
		path[i] = "V" + to_string(s) + "->V" + to_string(i);
	}
		
	for (int i = 1; i < LEN - 1; i++)
	{
		int min = inf, w = -1;
		for (int k = 1; k < LEN; k++)
		{
			if (!visit[k] && dist[k] < min)
				min = dist[w = k];
		}
		if (w == -1)
			break;
		visit[w] = 1;
		for (int k = 1; k < LEN; k++)
		{
			if (!visit[k] && Graph[w][k] != INT_MAX && dist[k] > dist[w] + Graph[w][k])
			{
				dist[k] = dist[w] + Graph[w][k];
				path[k] = path[w] + "->V" + to_string(k);
			}
		}
	}
	for (int i = 1; i < LEN; i++)
	{
		if(dist[i] != INT_MAX)
			cout << path[i] << " = " << dist[i] << endl;
		else
			cout << path[i] << " = " << "∞" << endl;
	}
	return 0;
}
int main()
{
	int start = 1;
	crateGraph();
	print();
	Dijkstra(start);
	return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章