Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph

This Java program is to find the number of spanning trees in a Complete Bipartite graph. This can be calculated using the matrix tree theorem or Cayley’s formula.

Here is the source code of the Java program to ind the number of spanning trees in a Complete Bipartite graph. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.Scanner;
  3. public class NumOfSpanningBipartite
  4. {
  5.     private int firstSetSize;
  6.     private int secondSetSize;
  8.     public int numberOfSpanningTree(int firstSetSize, int secondSetSize)
  9.     {
  10.         this.firstSetSize = firstSetSize;
  11.         this.secondSetSize = secondSetSize;
  12.         return (this.firstSetSize^(this.secondSetSize - 1)) *(this.secondSetSize ^ (this.firstSetSize -1)); 
  13.     }
  15.     public static void main(String...arg)
  16.     {
  17.         int m, n;
  18.         Scanner scanner = new Scanner(;
  19.         System.out.println("enter the size of the bipartite graph (m and n)");
  20.         m = scanner.nextInt();
  21.         n = scanner.nextInt();
  23.         NumOfSpanningBipartite bipartite = new  NumOfSpanningBipartite();
  24.         System.out.println(" the number of spanning trees are  " + bipartite.numberOfSpanningTree(m, n));
  25.         scanner.close();
  26.     }
  27. }

$java NumOfSpanningBipartite
enter the size of the bipartite graph (m and n)
2 2
 the number of spanning trees are  9

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

If you wish to look at all Java Programming examples, go to Java Programs.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.