Dijkstra算法是一种用于在加权图中找到最短路径的算法。它通过计算从起点到每个节点的最短路径来解决问题。Dijkstra算法适用于没有负权边的图。Dijkstra算法使用一个距离数组来记录从起点到每个节点的最短距离。它通过不断选择距离最短的节点来扩展搜索范围,直到找到目标节点或遍历完所有节点。
Dijkstra算法用于解决从一个节点到其他所有节点的最短路径问题,例如在地图上找到从一个城市到其他城市的最短路径,或者在网络中找到从一个节点到其他节点的最短路径。
import java.util.*;
class Node implements Comparable {
int id;
int distance;
public Node(int id, int distance) {
this.id = id;
this.distance = distance;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.distance, other.distance);
}
}
public class Dijkstra {
private int[][] graph;
private int numNodes;
public Dijkstra(int[][] graph, int numNodes) {
this.graph = graph;
this.numNodes = numNodes;
}
public int[] findShortestPath(int start) {
int[] distances = new int[numNodes];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[start] = 0;
PriorityQueue queue = new PriorityQueue<>();
queue.offer(new Node(start, 0));
while (!queue.isEmpty()) {
Node current = queue.poll();
for (int neighbor = 0; neighbor < numNodes; neighbor++) {
if (graph[current.id][neighbor] != 0) {
int distance = distances[current.id] + graph[current.id][neighbor];
if (distance < distances[neighbor]) {
distances[neighbor] = distance;
queue.offer(new Node(neighbor, distance));
}
}
}
}
return distances;
}
public static void main(String[] args) {
int[][] graph = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
int numNodes = graph.length;
int start = 0;
Dijkstra dijkstra = new Dijkstra(graph, numNodes);
int[] distances = dijkstra.findShortestPath(start);
for (int i = 0; i < numNodes; i++) {
System.out.println("Distance from node " + start + " to node " + i + ": " + distances[i]);
}
}
}