图最短路径之BellmanFord

定义

贝尔曼-福特算法,可以从给定一个图和图中的源顶点src,找到从src到给定图中所有顶点的最短路径。该图可能包含负权重边。相对于Dijkstra算法的优势是可以处理负权重边,缺点则是复杂度高于Dijkstra 。具体算法的详细解析请参考https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/,以下代码也是参考https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/,只是根据自己的需要增加了一些东西。

package graph.bellman_ford;
?
import lombok.Data;
?
public class Graph {
   private final int vertexCount;
   private final int edgeCount;
   private final Edge[] edge;
?
   public Graph(int vertexCount, int edgeCount, Edge[] edge) {
       this.vertexCount = vertexCount;
       this.edgeCount = edgeCount;
       this.edge = edge;
  }
?
   @Data
   public static class Edge {
       Vertex source;
       Vertex destination;
       int weight;
  }
?
   @Data
   public static class Vertex {
       int sequence;
       String code;
       String name;
  }
?
?
   public void bellmanFord(Graph graph, int src) {
       int[] distance = new int[vertexCount];
       
       for (int i = 0; i < vertexCount; ++i) {
           distance[i] = Integer.MAX_VALUE;
      }
       distance[src] = 0;
?
 
       for (int i = 1; i < vertexCount; ++i) {
           for (int j = 0; j < edgeCount; ++j) {
               int u = graph.edge[j].source.sequence;
               int v = graph.edge[j].destination.sequence;
               int weight = graph.edge[j].weight;
               if (distance[u] != Integer.MAX_VALUE && distance[u] + weight < distance[v]) {
                   distance[v] = distance[u] + weight;
              }
          }
      }
?
   
       for (int j = 0; j < edgeCount; ++j) {
           int u = graph.edge[j].source.sequence;
           int v = graph.edge[j].destination.sequence;
           
上一篇:性能测试——jmeter性能测试——配置元件——用户自定义变量


下一篇:JUC