【问题标题】:Algorithms in Java from Prim's MST to Dijkstra SPT从 Prim 的 MST 到 Dijkstra SPT 的 Java 算法
【发布时间】:2013-01-19 12:07:28
【问题描述】:

我正在关注Algorithms in Java, Part 5: Graph Algorithms, 3rd Edition 书中的code,在第 294 页中描述了我们可以通过修改 Prim 的最小生成树 (MST) 算法(我测试过并且工作正常)来获得经典的 Dijkstra 算法以下方式:将优先级分配从P = e->wt()边缘权重更改为P = wt[v] + e->wt()从源到边缘目的地的距离。问题是,当我进行更改时,随后的条件永远不会评估为true,这是可以理解的。 wt 是一个双数组,初始化为例如Double.MAX_VALUE 因此,无论 v 和 w 是什么,这个条件永远不会成立(假设非负权重):

P = wt[v] + e->wt();
if (P < wt[w]) { // this can never happen ... bug?
   // ...
} 

我查看了这本书的网站,没有发现任何勘误。

这是我的自包含代码版本,带有可运行的 Main 和书中的测试用例:

更新:

  • 在其中一个答案的反馈之后添加了初始化行wt[getSource().index] = 0.0;。源顶点属于距离为零的SPT。

    import java.util.*;
    
    public class AdjacencyList {
        //=============================================================
        // members
        //=============================================================
        private static class Edge {
            int source;
            int target;
            double weight;
        };
        private static class Vertex {
            int index;
            String name;
            List<Edge> edges = new ArrayList<Edge>();
            public Vertex(int index, String name) {
                this.index = index;
                this.name = name;
            }
        };
        private static final int UNDEFINED = -1;
        private int edgesCount = 0;
        private final Vertex[] vertices;
        private final boolean digraph;
        private int orderCount;
    
        //=============================================================
        // public
        //=============================================================
        public AdjacencyList(int verticesCount, boolean digraph) {
            this.vertices = new Vertex[verticesCount];
            this.digraph = digraph;
        }
    
        public Vertex createVertex(int index) {
            return createVertex(index, String.valueOf(index));
        }
    
        public Vertex createVertex(int index, String name) {
            Vertex vertex = new Vertex(index, name);
            vertex.index = index;
            vertex.name = name;
            vertices[index] = vertex;
    
            return vertex;
        }
    
        public Edge addEdge(int begin, int end, double weight) {
            return addEdge(vertices[begin], vertices[end], weight);
        }
    
        public Edge addEdge(Vertex begin, Vertex end, double weight) {
            edgesCount++;
            Edge edge   = new Edge();
            edge.source = begin.index;
            edge.target = end.index;
            edge.weight = weight;
            vertices[begin.index].edges.add(edge);
            if (!digraph) {
                Edge reverse = new Edge();
                reverse.source = end.index;
                reverse.target = begin.index;
                reverse.weight = edge.weight;
                vertices[end.index].edges.add(reverse);
            }
            return edge;
        }
    
        // inefficient find edge O(V)
        public Edge findEdge(int begin, int end) {
            Edge result = null;
            Vertex vertex = vertices[begin];
            List<Edge> adjacency = vertex.edges;
            for (Edge edge : adjacency) {
                if (edge.target == end) {
                    result = edge;
                    break;
                }
            }
            return result;
        }
    
        // inefficient remove edge O(V)
        public void removeEdge(int begin, int end) {
            edgesCount--;
            removeOneEdge(begin, end);
            if (!digraph) {
                removeOneEdge(end, begin);
            }
        }
    
        public final Vertex[] getVertices() {
            return vertices;
        }
    
        public int getVerticesCount() {
            return vertices.length;
        }
    
        public int getEdgesCount() {
            return edgesCount;
        }
    
        public Vertex getSource() {
            return vertices[0];
        }
    
        public Vertex getSink() {
            return vertices[vertices.length - 1];
        }
    
        public void dijkstra() {
            int verticesCount = getVerticesCount();
            double[] wt = new double[verticesCount];
            for (int i = 0; i < wt.length; i++) {
                wt[i] = Double.MAX_VALUE;
            }
            wt[getSource().index] = 0.0;
            Edge[] fr  = new Edge[verticesCount];
            Edge[] mst = new Edge[verticesCount];
            int min = -1;
            Edge edge = null;
            for (int v = 0; min != 0; v = min) {
                min = 0;
                for (int w = 1; w < verticesCount; w++) {
                    if (mst[w] == null) {
                        double P = 0.0;
                        edge = findEdge(v, w);
                        if (edge != null) {
                            if ((P = wt[v] + edge.weight) < wt[w]) {
                                wt[w] = P;
                                fr[w] = edge;
                            }
                        }
    
                        if (wt[w] < wt[min]) {
                            min = w;
                        }
                    }
                }
    
                if (min != 0) {
                    mst[min] = fr[min];
                }
            }
    
            for (int v = 0; v < verticesCount; v++) {
                if (mst[v] != null) {
                    System.out.print(mst[v].source + "->" + mst[v].target + " ");
                }
            }
        }
    
        public void pushRelabel() {
            // TODO
        }
    
        //=============================================================
        // private
        //=============================================================
    
        private void removeOneEdge(int begin, int end) {
            Vertex beginVertex = vertices[begin];
            List<Edge> adjacency = beginVertex.edges;
            int position = -1;
            for (int i = 0; i < adjacency.size(); i++) {
                if (adjacency.get(i).target == end) {
                    position = i;
                    break;
                }
            }
            if (position != -1) {
                adjacency.remove(position);
            }
        }
    
        private static AdjacencyList createDijkstraGraph() {
            int numberOfVertices = 6;
            boolean directed = true;
            AdjacencyList graph = new AdjacencyList(numberOfVertices, directed);
            for (int i = 0; i < graph.getVerticesCount(); i++) {
                graph.createVertex(i);
            }
            graph.addEdge( 0, 1, .41);
            graph.addEdge( 1, 2, .51);
            graph.addEdge( 2, 3, .50);
            graph.addEdge( 4, 3, .36);
            graph.addEdge( 3, 5, .38);
            graph.addEdge( 3, 0, .45);
            graph.addEdge( 0, 5, .29);
            graph.addEdge( 5, 4, .21);
            graph.addEdge( 1, 4, .32);
            graph.addEdge( 4, 2, .32);
            graph.addEdge( 5, 1, .29);
            return graph;
        }
    
        /**
         * Test main
         *
         * @param args
         */
        public static void main(String[] args) {
            // build the graph and test dijkstra shortest path
            AdjacencyList directedDijkstra = createDijkstraGraph();
            // expected:
            System.out.println("\n\n*** testing dijkstra shortest path");
            directedDijkstra.dijkstra();
        }
    }
    

【问题讨论】:

    标签: java algorithm


    【解决方案1】:

    你弄错了,因为 v != w, wt[v] + e->wt() 可以小于 wt[w]。实际错误是需要设置wt[source] = 0(dijkstra是单源最短路径,需要源!)!关于这本书:如果他们忘记了那部分,那他们就不好了:-P

    【讨论】:

    • 谢谢。很好,但是算法仍然不起作用:(
    • 好的,我检查了会发生什么,条件if (wt[w] &lt; wt[min]) 永远不会为真,因为wt[min] 当min == source 为零时。
    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2011-03-26
    • 2012-12-18
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多