邻接表结构
#define MaxVertexNum 100
typedef struct ArcNode
{
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct Vnode
{
int data;
ArcNode *first;
}Vnode,AdjList[MaxVertexNum];
typedef struct
{
AdjList vertices;
int vexnum=0,arcnum=0;
}ALGraph;
创建邻接表
ALGraph* CreateAG1()
{
ALGraph *G = new ALGraph();
G->vexnum = 4;
G->arcnum = 3;
for(int i=0;i<G->vexnum;i++)
{
G->vertices[i].data = i;
G->vertices[i].first = NULL;
}
for(int i=0;i<G->arcnum;i++)
{
ArcNode *p = new ArcNode();
p->adjvex = i+1 ; p->next= NULL;
G->vertices[i].first = p;
}
return G;
}
ALGraph* CreateAG2()
{
ALGraph *G = new ALGraph();
G->vexnum = 6;
G->arcnum = 4;
for(int i=0;i<G->vexnum;i++)
{
G->vertices[i].data = i;
G->vertices[i].first = NULL;
}
for(int i=0;i<3;i++)
{
ArcNode *p = new ArcNode();
p->adjvex = i+1 ; p->next= NULL;
G->vertices[i].first = p;
}
ArcNode *p = new ArcNode();
p->adjvex = 5;
p->next = G->vertices[1].first;
G->vertices[1].first = p;
ArcNode *q = new ArcNode();
q->adjvex = 4;
q->next = G->vertices[2].first;
G->vertices[2].first = q;
return G;
}
打印邻接表
void Print(ALGraph *G)
{
for(int i=0;i<G->vexnum;i++)
{
cout<<G->vertices[i].data<<"-->";
ArcNode *p = G->vertices[i].first;
while(p!=NULL)
{
cout<<p->adjvex<<"-->";
p=p->next;
}
cout<<"NULL"<<endl;
}
}
DFS判断
void DFS_Judge(ALGraph *G, int i, int j,bool &Reach)
{
if(i==j||Reach==true)
{
Reach = true;
return ;
}
visited[i] = 1;
for(int w = FirstNeighbor(G,i);w>=0;w=NextNeighbor(G,i,w))
{
if(!visited[w] &&!Reach)
DFS_Judge(G,w,j,Reach);
}
}
BFS判断
queue<int> Q;
void BFS_Judge(ALGraph *G,int i,int j, bool &Reach)
{
Q.push(i);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
visited[u] = 1;
if(u==j) Reach =true;
for(int w=FirstNeighbor(G,u);w>=0;w = NextNeighbor(G,u,w))
{
if(w==j)
{
Reach =true; return ;
}
if(!visited[w])
{
Q.push(w);
visited[w]=1;
}
}
}
}
main函数
int main()
{
ALGraph *G=CreateAG1();
ALGraph *H =CreateAG2();
Print(G); Print(H);
bool Reach1 = false, Reach2 = false;
DFS_Judge(G,0,1,Reach1);
DFS_Judge(H,3,4,Reach2);
cout<<Reach1<<" "<<Reach2 <<endl;
fill(visited.begin(),visited.end(),0);
Reach1 = false, Reach2 = false;
BFS_Judge(G,0,1,Reach1);
BFS_Judge(H,2,4,Reach2);
cout<<Reach1<<" "<<Reach2 <<endl;
system("pause");
return 0;
}