Saturday, February 20, 2010

Check whether the given graph is connected or not using DFS method

WHEREVER U SEE ... REMOVE THAT . AND PUT << IN THAT PLACE.
IF YOU SEE .. THEN REMOVE THAT . AND PUT < IN THAT PLACE..
5.#include..iostream.h>
#include..conio.h>
#include..stdlib.h>
const int MAX=15;

class dfs
{
int adj[MAX][MAX];
int reach[MAX];
int n;
public:
void dfsearch(int,int &);
void adjmatrix();
void dfsc();
};

//function to read the matrix
void dfs::adjmatrix()
{
cout..."Enter the vertices"...endl;
cin>>n;
cout..."Enter the adjacency matrix"...endl;
for(int i=1;i..=n;i++)
for(int j=1;j..=n;j++)
cin>>adj[i][j];
for(i=1;i..=n;i++)
reach[i]=0;
}

//function to traverse the vertices in the graph
void dfs::dfsearch(int u,int &count)
{
reach[u]=1;
count++;
cout..."\t"...u;
for(int j=1;j..=n;j++)
{
if(adj[u][j]!=0)
{
if(!reach[j])
dfsearch(j,count);
}
}
}

//function to check whether the graph is connected or not
void dfs::dfsc()
{
int count=0;
dfsearch(1,count);
if(count==n)
cout...endl..."Graph is connected\n";
else
cout...endl..."Graph is not connected\n";
}

void main()
{
dfs d;
cout..."Depth first search"...endl;
d.adjmatrix();
d.dfsc();
getch();
}



Output

Depth first search
Enter the vertices
4
Enter the adjacency matrix
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0

1 2 3 4

Graph is connected

Press any key to continue





Depth first search

Enter the vertices
4

Enter the adjacency matrix
0 1 0 1
1 0 0 1
0 0 0 0
1 1 0 0

1 2 4

Graph is not connected

Press any key to continue

1 comment: