在Java中,常用的最短路径算法包括迪杰斯特拉算法(Dijkstra's Algorithm)和弗洛伊德算法(Floyd's Algorithm)。下面我将为您提供这两个算法的简单实现示例:
-
迪杰斯特拉算法(Dijkstra's Algorithm):
import java.util.*;
public class DijkstraAlgorithm {
public static int[] dijkstra(int[][] graph, int source) {
int n = graph.length;
int[] distance = new int[n];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[source] = 0;
boolean[] visited = new boolean[n];
for (int count = 0; count < n - 1; count++) {
int minDistance = Integer.MAX_VALUE;
int minIndex = -1;
for (int v = 0; v < n; v++) {
if (!visited[v] && distance[v] <= minDistance) {
minDistance = distance[v];
minIndex = v;
}
}
visited[minIndex] = true;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[minIndex][v] != 0 && distance[minIndex] != Integer.MAX_VALUE &&
distance[minIndex] + graph[minIndex][v] < distance[v]) {
distance[v] = distance[minIndex] + graph[minIndex][v];
}
}
}
return distance;
}
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 source = 0;
int[] distance = dijkstra(graph, source);
System.out.println("最短路径:");
for (int i = 0; i < distance.length; i++) {
System.out.println("从节点 " + source + " 到节点 " + i + " 的距离为 " + distance[i]);
}
}
}
2.弗洛伊德算法(Floyd's Algorithm):
import java.util.*;
public class FloydAlgorithm {
public static void floyd(int[][] graph) {
int n = graph.length;
int[][] distance = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
distance[i][j] = graph[i][j];
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (distance[i][k] != Integer.MAX_VALUE && distance[k][j] != Integer.MAX_VALUE &&
distance[i][k] + distance[k][j] < distance[i][j]) {
distance[i][j] = distance[i][k] + distance[k][j];
}
}
}
}
System.out.println("最短路径:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (distance[i][j] == Integer.MAX_VALUE) {
System.out.print("INF ");
} else {
System.out.print(distance[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 5, Integer.MAX_VALUE, 10},
{Integer.MAX_VALUE, 0, 3, Integer.MAX_VALUE},
{Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1},
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0}
};
floyd(graph);
}
}