A graph is said to be a tree when it has no cyclic path in it .
So the program focuses to find out whether the given graph is acyclic
by using a two dimensional array of size m*n.
Each row contains the max limit of array,start node and the adjacent nodes from
the previous node.Last index is a flag which is used in case of undirected graph
as here.
In undirected graph when 1-2 is the edge , there is an edge also from 2-1.
Eg :-we prove that the graph
given by the input :
3 3
1 2
1 3
2 3
is cyclic as shown in the diagram.
If for any row , the first and the last element are same,
then the graph is cyclic,that is not a tree.Here in the second row ,node 2 comes
in front and rear.
The program is described as follows..
#include<stdio.h>
#include<stdlib.h>
void print( int **a,int n, int m)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<a[i][0];j++)printf("%d ",a[i][j]);
printf("\n");
}
printf("\n");
}
int main()
{
int n,m,i,j,k,r,c,**a,flag=0,temp,*pos;
scanf("%d%d",&n,&m);
pos=(int *)malloc(n*sizeof(int));
a=(int **)malloc(n*sizeof(int *));
for(i=0;i<n;i++)a[i]=(int *)malloc((m+2)*sizeof(int));
for(i=0;i<n;i++){ a[i][1]=i+1; a[i][0]=2;}
for(i=0;i<m;i++)
{
scanf("%d%d",&r,&c);
for(k=0;k<n;k++)pos[k]=0;
if(r==c){ flag=1; break;}
if(r!=c)
{
for(j=0;j<n;j++)
{
if(a[j][a[j][0]-1]==r){ a[j][a[j][0]]=c; a[j][0]++; pos[j]=1; }
}
for(j=0;j<n;j++)
{
if(pos[j]==0&&a[j][a[j][0]-1]==c){ a[j][a[j][0]]=r; a[j][0]++; }
}
print(a,n,m);
}
}
if(flag==1){printf("NOT A TREE\n"); return 0; }
for(i=0;i<n;i++)
{
if(a[i][0]>2&&a[i][1]==a[i][a[i][0]-1]){printf("YES\n"); return 0;}
}
printf("TREE\n");
}

