Untitled

 avatar
unknown
java
2 years ago
1.5 kB
5
Indexable
public class Prim {

    public static int shortestPath(Graph g, Vertex v) {

        //Create a new MST set that keeps track of vertices already included in MST
        Set<Vertex> mstSet = new HashSet<>();

        int maxValue = Integer.MAX_VALUE;

        //Create Prioritylist
        AdaptablePQ pq = new AdaptablePQ();
        pq.insertOrReplace(v, 0);

        //Create array to store the min key value of each vertex
        //Set all the values to Max value
        int[] arrayDistance = new int[g.getAllVertices().size()];
        for (int i = 0; i < arrayDistance.length; i++) {
            arrayDistance[i] = Integer.MAX_VALUE;
        }
        arrayDistance[v.getId()] = 0;

        //While pq is not empty
        while (pq.size() != 0) {

            VertexNumPair pair = pq.removeMin();
            Vertex vertex1 = pair.getVertex();

            mstSet.add(vertex1);

            for (VertexNumPair currNeighbors : pair.getVertex().getNeighbours()) {

                if (currNeighbors.getNum() < arrayDistance[currNeighbors.getVertex().getId()]) {
                    arrayDistance[currNeighbors.getVertex().getId()] = currNeighbors.getNum();
                    pq.insertOrReplace(currNeighbors.getVertex(), currNeighbors.getNum());
                }

            }

        }


        int total = 0;
        for (int i = 0; i < arrayDistance.length; i++) {
            total += arrayDistance[i];
        }
        return total;
    }

    }
Editor is loading...