單源最短路徑--Bellman-Ford算法

BELLMAN-FORD最短路徑算法:

BELLMAN-FORD(G,w,s)
1 INITIALIZE-SINGLE-SOURCE(G,s)
2 for i = 1 to |G.V| - 1
3   for each edge(u,v) belong to G.E
4      RELAX(u,v,w)
5 for each edge(u,v) belong to G.E
6   if v.d > u.d + w(u,v)
7     return FALSE
8 return TRUE

初始化算法:

INITIALIZE-SINGLE-SOURCE(G,s)
1 for each vertex v belong to G.V
2   v.d = infty
3   v.pi = NIL
4 s.d = 0

鬆弛操作:

RELAX(u,v,w)
1 if v.d > u.d + w(u,v)
2   v.d = u.d + w(u,v)
3   v.pi = u

java實現代碼如下:

    /** * 初始化操作 * @param vertexs * @param startID */
    public static void initialize_single_source(List<Vertex> vertexs, int startID){
        for (Vertex vertex : vertexs){
            vertex.setD(50000);
            vertex.setParent(null);
        }
        Vertex start = Vertex.getVertex(startID);
        start.setD(0);
    }

    /** * 鬆弛操作 * @param u * @param v * @param w 邊(u,v) * @throws Exception */
    public static void relax(Edge w){
        if (w.getDest().getD() > w.getStart().getD() + w.getWeight()){
            w.getDest().setD(w.getStart().getD() + w.getWeight());
            w.getDest().setParent(w.getStart());
        }       
    }

    public static boolean bellman_ford(String graphContent, int startID){
        List<Vertex> vertexs = Route.getVertexs(graphContent);
        initialize_single_source(vertexs, startID);
        Edge[] edges = Route.getEdges(graphContent);

        for (int i = 0; i < edges.length; i++){
            for (Edge edge : edges){
                relax(edge);
            }
        }
        for (Edge edge : edges){
            if (edge.getDest().getD() > edge.getStart().getD() + edge.getWeight()){
                return false;
            }
        }
        return true;
    }

    /** * 打印最短路徑 * @param graphContent * @param startID * @param destID */
    public static void print_Path(String graphContent, int startID, int destID){
        if (bellman_ford(graphContent, startID)){
            Vertex v = Vertex.getVertex(destID);
            if (v.equal(startID)){
                System.out.print(Vertex.getVertex(startID)+ "(" + Vertex.getVertex(startID).getD() + ")--");
            }else if (v.getParent() == null){
                System.out.println("\nno path from \"s\" to \"v\" exists");
            }else {
                print_Path(graphContent, startID, v.getParent().getID());
                System.out.print(v + "(" + v.getD() + ")--");
            }
        }
    }
点赞