SPFA算法java
时间: 2023-10-12 16:06:18 浏览: 105
SPFA算法(Shortest Path Faster Algorithm)是一种用于解决单源最短路径问题的图算法。下面是一个使用Java实现的SPFA算法示例:
```java
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class SPFAAlgorithm {
private static final int INF = Integer.MAX_VALUE; // 无穷大
public static void spfa(int[][] graph, int source, int[] dist) {
int n = graph.length; // 图中节点个数
Arrays.fill(dist, INF); // 初始化距离数组
boolean[] visited = new boolean[n]; // 记录节点是否被访问过
Queue<Integer> queue = new LinkedList<>();
queue.offer(source);
visited[source = true;
dist[source = 0;
while (!queue.isEmpty()) {
int currNode = queue.poll();
visited[currNode = false;
for (int i = 0; i < n; i++) {
if (graph[currNode][i != INF && dist[currNode + graph[currNode][i < dist[i]) {
dist[i = dist[currNode + graph[currNode][i];
if (!visited[i]) {
queue.offer(i);
visited[i = true;
}
}
}
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 1, 3, INF},
{INF, 0, INF, 2},
{INF, INF, 0, INF},
{INF, INF, 1, 0}
};
int source = 0; // 源节点
int[] dist = new int
阅读全文