ZenXiu
ZenXiu

Reputation: 21

Kruskal Algorithm: Display adjacency matrix from weighted matrix

I am a beginner in java and is tasked to make a Java program implementing Kruskal's algorithm. The program should display the adjacency matrix and minimum cost. I have done the following code. It displays the minimum cost but I don't know how to display the adjacency matrix from the weighted matrix input.

 import java.util.Scanner;

    public class kruskal 
    {
        int parent[]=new int[10];
        int find(int m)
        {
            int p=m;
            while(parent[p]!=0)
            p=parent[p];
            return p;
        }

        void union(int i,int j)
        {

            if(i<j)
            parent[i]=j;
            else
            parent[j]=i;
        }

        void krkl(int[][]a, int n)
        {
            int u=0,v=0,min,k=0,i,j,sum=0;

            while(k<n-1)
            {
                min=99;
                for(i=1;i<=n;i++)
                for(j=1;j<=n;j++)

                if(a[i][j]<min&&i!=j)
                {
                    min=a[i][j];
                    u=i;
                    v=j;
                }

                i=find(u);
                j=find(v);

                if(i!=j)
                {
                    union(i,j);
                    System.out.println("("+u+","+v+")"+"="+a[u][v]);
                    sum=sum+a[u][v];
                    k++;
                }

                a[u][v]=a[v][u]=99;
            }
            System.out.println("The cost of minimum spanning tree = "+sum);
        }


        public static void main(String[] args) {

            Scanner sc=new Scanner(System.in);
            kruskal k=new kruskal();
            char ch;

            do
            {
                int a[][]=new int[10][10];
                int i,j;
                int n;
                System.out.println("Enter the number of vertices of the graph");
                n=sc.nextInt();

                System.out.println("Enter the weighted matrix");
                for(i=1;i<=n;i++)
                for(j=1;j<=n;j++)
                a[i][j]=sc.nextInt();
                System.out.println();
                k.krkl(a,n);

                System.out.println("\nDo you want to continue? (Type y or n) \n");
                ch = sc.next().charAt(0);
                
            } while (ch == 'Y'|| ch == 'y');
        }
            
    }

Any help on how would I do this? I am trying to have an input like this:

     1  2   3   4
   1 1  0   0   0
   2 0  1   1   0
   3 0  1   1   0
   4 0  0   0   1

Upvotes: 1

Views: 347

Answers (0)

Related Questions