单源最短路径Dijkstra和优先级算法

时间:2022-11-20 00:13:04

百度百科:迪杰斯特拉算法。

代码实现如下:

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner; class Node
{
int x;
int value;
}
public class Main
{
static int N,M,cnt;
static final int MAX = 105;
static final int INF = 1000009;
static Node node[] = new Node[MAX];
static int map[][] = new int[MAX][MAX];
static int distence[] = new int[MAX];
static boolean vis[] = new boolean[MAX];
public static void main(String []args)
{
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
N = cin.nextInt();
M = cin.nextInt();
if(N == 0)
{
return;
}
cnt = 0;
for(int i = 0; i < M; i++)
{
int a = cin.nextInt();
int b = cin.nextInt();
int c = cin.nextInt();
map[a][b] = c;
map[b][a] = c;
}
Dijkstra(N,M);
for(int i = 1; i <= N; i++)
{
System.out.println(distence[i]);
}
}
}
static void Dijkstra(int N,int M)
{
Init();
PriorityQueue <Node> que = new PriorityQueue<Node>(MAX,new Comparator<Node>()
{
public int compare(Node o1, Node o2)
{
if(o1.value > o2.value)
{
return 1;
}
else if(o1.value == o2.value)
{
return 0;
}
else
{
return -1;
}
} });
for(int i = 2; i <= N; i++)
{
if(map[1][i] != 0)
{
node[cnt].x = i;
node[cnt].value = map[1][i];
que.add(node[cnt]);
cnt++;
}
}
while(!que.isEmpty())
{
Node a = new Node();
a = que.poll();
if(vis[a.x] == true)
{
continue;
}
vis[a.x] = true;
for(int i = 2; i <= N; i++)
{
if(vis[a.x] == false && distence[i] > distence[a.x]+map[a.x][i])
{
distence[i] = distence[a.x]+map[a.x][i];
node[cnt].x = i;
node[cnt].value = map[a.x][i];
cnt++;
}
}
}
}
static void Init()
{
node[0] = new Node();
node[1] = new Node();
for(int i = 2; i <= N; i++)
{
if(map[1][i] != 0)
{
distence[i] = map[1][i];
}
else
{
distence[i] = INF;
}
node[i] = new Node();
}
}
}