Transitive closure of a Graph

PROBLEM :

Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Here reachable mean that there is a path from vertex i to j. The reach-ability matrix is called transitive closure of a graph.

Input:
First line consists of T test cases. First line of every test case consists of N , denoting number of vertices. Second line consists of N*N spaced integer(Only 0 and 1), denoting the edge b/w i to j.

Output:
Single line output, print the trasitive closure formed of graph.

Constraints:
1<=T<=100
1<=N<=100

Example:
Input:
1
4
1 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1

Output:
1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (using Floyd Warshall)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#define MAX 1000
void FloydWarshall(int graph[MAX][MAX],int ) ;

int main()
{
int t ;
cin>>t ;

while(t--)
{
   int no ;
   cin>>no ;
 
   int graph[MAX][MAX] ;
   for(int i=0;i<no;i++)
       for(int j=0;j<no;j++)
           cin>>graph[i][j] ;
         
   FloydWarshall(graph,no) ;
   cout<<endl ;
}
return 0;
}

void FloydWarshall(int graph[MAX][MAX],int no)
{
    int path[MAX][MAX] ;
   
    for(int i=0;i<no;i++)
        for(int j=0;j<no;j++)
            path[i][j]=graph[i][j] ;
           
    for(int k=0;k<no;k++)
    {
        for(int j=0;j<no;j++)
        {
            for(int i=0;i<no;i++)
            {
                path[i][j] = path[i][j] || (path[i][k] && path[k][j]) ;
            }
        }
    }
   
    for(int i=0;i<no;i++)
  for(int j=0;j<no;j++)
      cout<<path[i][j]<<" " ;
   
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )