图的最短路径 java
时间: 2024-01-08 07:20:19 浏览: 71
以下是使用Java实现图的最短路径的示例代码:
1. 使用Dijkstra算法求某一个顶点到其他各顶点的最短路径:
```java
import java.util.*;
public class DijkstraAlgorithm {
private static final int INF = Integer.MAX_VALUE;
public static void dijkstra(int[][] graph, int start) {
int n = graph.length;
int[] dist = new int[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, INF);
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
int u = -1;
for (int j = 0; j < n; j++) {
if (!visited[j] && (u == -1 || dist[j] < dist[u])) {
u = j;
}
}
visited[u] = true;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] != 0 && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
System.out.println("Shortest paths from vertex " + start + ":");
for (int i = 0; i < n; i++) {
if (dist[i] == INF) {
System.out.println("Vertex " + i + ": No path");
} else {
System.out.println("Vertex " + i + ": " + dist[i]);
}
}
}
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}
};
dijkstra(graph, 0);
}
}
```
2. 使用Floyd算法求图中任意两个顶点的最短路径:
```java
import java.util.*;
public class FloydAlgorithm {
private static final int INF = Integer.MAX_VALUE;
public static void floyd(int[][] graph) {
int n = graph.length;
int[][] dist = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[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 (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
System.out.println("Shortest paths between all pairs of vertices:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(dist[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 4, INF, INF, INF, INF, INF, 8, INF},
{4, 0, 8, INF, INF, INF, INF, 11, INF},
{INF, 8, 0, 7, INF, 4, INF, INF, 2},
{INF, INF, 7, 0, 9, 14, INF, INF, INF},
{INF, INF, INF, 9, 0, 10, INF, INF, INF},
{INF, INF, 4, 14, 10, 0, 2, INF, INF},
{INF, INF, INF, INF, INF, 2, 0, 1, 6},
{8, 11, INF, INF, INF, INF, 1, 0, 7},
{INF, INF, 2, INF, INF, INF, 6, 7, 0}
};
floyd(graph);
}
}
```
阅读全文