Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (1.5k points)
I was trying to use Prim's algorithm in Java but I am unable to do that. Can anybody help me to do that?

Thanks

1 Answer

0 votes
by (1.4k points)

Prim’s algorithm is an algorithm which takes weighted, undirected, connected graph as an input and returns MST of a graph as an output. 

This works in a greedy manner which means it selects an arbitrary vertex and then selects the nearest vertex until there is no disconnected vertex left vertex. 

Prims Algorithms Implementation In Java - Minimum Cost Spanning Tree

public class PrimS { 

    int weightArray[][] = new int[20][20]; 

    int visited[] = new int [20]; 

    int d[] = new int[20]; 

    int p[] = new int[20]; 

    int verticeCountedgeCount; 

    int nodeAnodeB, weight; 

    int current, total, mincost; 

    public static void main(Strinargs[]) throws IOException { 

        // Instantiate the graph based on input 

        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 

        System.out.print("\nEnter number of vertices: "); 

        verticeCount = Integer.parseInt(buf.readLine()); 

        System.out.print("\nEnter number of edges: "); 

        edgeCount = Integer.parseInt(buf.readLine()); 

        for (int i = 1i <= verticeCounti++) { 

            for(int j = 1; j <= verticeCountj++) { 

                weightArray[i][j] = 0; 

            } 

        } 

       for (int i = 1i <= verticeCounti++) { 

           p[i] = visited[i] = 0; 

           d[i] = 32767; 

        } 

        for (int i = 1i <= edgeCounti++) { 

            System.out.print("\nEnter edge nodeAnodeB anweightArray weight: "); 

            nodeA=Integer.parseInt(in.readLine()); 

            nodeB=Integer.parseInt(in.readLine()); 

            weight=Integer.parseInt(in.readLine()); 

            weightArray[nodeA][nodeB] = weightArray[nodeB][nodeA] = weight; 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 4, 2021 in Python by laddulakshana (16.4k points)

Browse Categories

...