Using DFS to solvethe following problems:
(1) given a graph G, test if G is connected.
(2) given a graph G, test if G has a cycle,ifso,print a cycle
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#define N 50
using namespace std;
int MaxNode=0;
int edgeNumber=0;
//The struct for the list node.
typedef struct ArcNode
{
int adjvex;
ArcNode *next;
}ArcNode;
//The struct for the list of vertex node.
typedef struct VertexNode
{
int vertex;
ArcNode *firstarc;
}VertexNode;
VertexNode AdjList[N]; //definition of the adjList array.
int visited[N]; //status of the node represent whether it has been visited or not.
//The function of reading a graph.
int ReadGraph()
{
ifstream fin("graph.txt");
const int LINE_LENGTH = 100;
char str[LINE_LENGTH];
for(int i=1;i<=N;i++)
{
AdjList[i].vertex=i;
AdjList[i].firstarc=NULL;
}
cout<<"The datas are:"<<endl;
while( fin.getline(str,LINE_LENGTH) )
{
edgeNumber++;
int i,j,k;
i=(int)(str[0]-'0');
j=(int)(str[2]-'0');
k=(i>=j)?i:j;
MaxNode=(MaxNode>=k)?MaxNode:k;
ArcNode *p;
ArcNode *q;
p=new ArcNode;
q=new ArcNode;
p->adjvex=i;
q->adjvex=j;
p->next=AdjList[j].firstarc;
AdjList[j].firstarc=p;
q->next=AdjList[i].firstarc;
AdjList[i].firstarc=q;
}
//Build the ajicency list.
for(int i=1;i<=MaxNode;i++)
{
cout<<AdjList[i].vertex<<"---";
ArcNode *p;
p=AdjList[i].firstarc;
while(p)
{
cout<<p->adjvex<<",";
p=p->next;
}
cout<<endl;
}
fin.close();
return edgeNumber;
}
//The function DFS.
void DFS_AdjList(int v)
{
ArcNode *p;
visited[v]=1;
MaxNode--;
cout<<AdjList[v].vertex<<",";
p=AdjList[v].firstarc;
while(p)
{
if(!visited[p->adjvex])
DFS_AdjList(p->adjvex);
p=p->next;
}
}
//The function to test if the graph is connected based on the DFS_AdjList function.
void TestConnection(int n,int e)
{
if(e<n-1)
{
cout<<"The Graph is not connected!"<<endl;
}
else
{
if(e>n*(n-1)/2)
cout<<"The Graph is connected!"<<endl;
else
{
for(int i=1;i<n;i++)
visited[i]=0;
cout<<"Please input the node you want to start testing: ";
int start;
cin>>start;
cout<<"The DFS searching path is: ";
DFS_AdjList(start);
cout<<endl;
if(MaxNode==0)
cout<<"The Graph is connected!"<<endl;
else
cout<<"The Graph is not connected!"<<endl;
}
}
}
//Main function.
int main()
{
ReadGraph();
TestConnection(MaxNode,edgeNumber);
system("PAUSE");
return 0;
}