📅  最后修改于: 2023-12-03 15:00:24.886000             🧑  作者: Mango
Dijkstra算法是一种贪心算法,用于在加权图中寻找从一个源节点到其他所有节点的最短路径。该算法迭代地选择距离源节点最近的未标记节点,将其标记,并更新与该节点相邻的节点的距离值。这个过程一直重复直到所有的节点都被标记,或者不能从源节点到达未标记节点。
以下是一个基于Java实现Dijkstra算法的示例代码:
import java.util.*;
public class DijkstraAlgorithm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] graph = new int[n][n];
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
int w = scanner.nextInt();
graph[u - 1][v - 1] = w;
graph[v - 1][u - 1] = w;
}
int start = scanner.nextInt() - 1;
int[] dist = new int[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Pair> pq = new PriorityQueue<>();
pq.offer(new Pair(start, 0));
while (!pq.isEmpty()) {
Pair top = pq.poll();
int u = top.vertex;
if (visited[u]) {
continue;
}
visited[u] = true;
for (int v = 0; v < n; v++) {
if (graph[u][v] > 0 && !visited[v] && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
pq.offer(new Pair(v, dist[v]));
}
}
}
for (int i = 0; i < n; i++) {
if (i != start) {
System.out.println(i + 1 + " " + dist[i]);
}
}
scanner.close();
}
}
class Pair implements Comparable<Pair> {
int vertex;
int weight;
public Pair(int vertex, int weight) {
this.vertex = vertex;
this.weight = weight;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(weight, o.weight);
}
}
i d
,其中i表示节点编号,d表示节点到起始节点的最短距离。本文介绍了Dijkstra算法的实现过程,使用Java语言演示了该算法的运行结果。使用该算法可以在加权图中寻找最短路径。