C++ Program to Find the Transitive Closure of a Graph

This C++ program displays the transitive closure matrix of a graph. The reachability of a particular node ‘i’ towards all node pairs (‘i’,’j’) is known as the transitive closure of a graph.

Here is the source code of the C++ program to display the transitive closure of a particular directed graph consisting of four nodes. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2.  * C++ Program to Find Transitive Closure of a Graph
  3.  */
  4. #include<stdio.h>
  5. #include<conio.h>
  6. #include<iostream>
  7. using namespace std;
  8. void printSolution(int reach[][4])
  9. {
  10.     cout<<"Following matrix is transitive closure of the given graph\n";
  11.     for (int i = 0; i < 4; i++)
  12.     {
  13.         for (int j = 0; j < 4; j++)
  14.         {
  15.             cout<<reach[i][j];
  16.         }
  17.         cout<<endl;
  18.     }
  19. }
  20. void transitiveClosure(int graph[][4])
  21. {
  22.     int reach[4][4], i, j, k;
  23.     for (i = 0; i < 4; i++)
  24.     {
  25.         for (j = 0; j < 4; j++)
  26.         {
  27.             reach[i][j] = graph[i][j];
  28.         }
  29.     }
  30.     for (k = 0; k < 4; k++)
  31.     {
  32.         for (i = 0; i < 4; i++)
  33.         {
  34.             for (j = 0; j < 4; j++)
  35.             {
  36.                 reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
  37.             }
  38.         }
  39.     }
  40.     printSolution(reach);
  41. }
  42. int main()
  43. {
  44.     int graph[4][4] = { {1, 1, 0, 1},
  45.                         {0, 1, 1, 0},
  46.                         {0, 0, 1, 1},
  47.                         {0, 0, 0, 1}
  48.                       };
  49.     transitiveClosure(graph);
  50.     getch();
  51. }

Output
Following matrix is transitive closure of the given graph
1111
0111
0011
0001

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
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.