简体   繁体   中英

Prim's algorithm, using a priority queue

I'm trying to implement prim's algorithm, using a priority queue. When I call offer() method, it gives me a class cast exception, saying that vertex cannot be cast to comparable. Is there a workaround?

public static Collection<Edge> prims(Graph g, int start) {
            ArrayList<Edge> mst = new ArrayList<Edge>();
            PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>();
            Vertex startVertex;

        for (Vertex vertex : g.getVertices()) {
            vertices.offer(vertex);
            if (vertex.getId() == start) {
                startVertex = vertex;
            }
        }

        if (!mst.isEmpty()) {
            return mst;
        }

        return null;
    }
}

Prims algorithm uses the weight of the edge to determine the best path. Posting the vertex to the PriorityQueue will not work.

I am guessing your Edge class will implement Comparable by comparing their lengths.

Yes: you need your Vertex method to implement Comparable<Vertex> .

Java's PriorityQueue is an implementation of a heap, which has log-time insertion, and log-time removal of the minimum element. But in order for that to be meaningful, you need to have a notion of minimum ; and that means you need whatever you put into a PriorityQueue to be Comparable , so that two elements in the heap can be compared.

The reason that non- Comparable elements can be inserted into a PriorityQueue is that you can also specify a Comparator in the constructor, rather than using Comparable elements. So as an alternative, you could leave your Vertex class as it is, but use the appropriate constructor (which also requires you to specify an initial capacity):

PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>(11,
    new Comparator<Vertex>() {
        //implement .compare() and .equals()
    });

The solution is to have your Vertex class implement Comparable , or to provide a Comparator to the priority queue when constructing it. The Java collections framework needs a way to compare your vertices (after all you're putting them into a priority queue and priority implies the necessity of some ordering being present).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM