邻接表的深度遍历(DFS)

https://blog.csdn.net/Achenming1314/article/details/105203878

#include <iostream>
/**
 *DFS usage:Refer to the hype data  structure
 */
using namespace std;
#define  maxvertex   100
typedef  char vertextype;   //vertex
typedef  int Edgetype ;     //edge
//define linklist node
typedef  struct EdgeNode{
    int adjvex ;//adjvex  store the  index of  vertex
    Edgetype  weight;
    struct EdgeNode *next;  //list
}EdgeNode;
//define array  which  can be used to store the vertex
typedef struct  VertexNode{
    vertextype data;
    EdgeNode*  firstedge  ;//Edge pointer
}VertexNode,Adjlist[maxvertex];
//define  grapha  which describe the  numbers of vertex and edge
typedef  struct {
   Adjlist  adjlist;
   int numvertex,numedge;
}GraphAdjlist;
//establish the grapha
void CreateALGrapha(GraphAdjlist *G){
   int i,j,k;
   EdgeNode *e;
   cout<<"input  the  numbers of  vertex and  edge:"<< endl;
   cin>>G->numvertex>>G->numedge;
   cout<<"input the information of vertex"<<endl;
   for(i=0;i<G->numvertex;i++){
       cin>>G->adjlist[i].data;
       G->adjlist[i].firstedge=NULL;
   }
   for(k=0;k<G->numedge;k++){
      //establish
       cout<<"input (Vi,Vj) number:"<<endl;
       cin>> i>>j;
       e=(EdgeNode*)malloc(sizeof(EdgeNode));
       e->adjvex=j;  //index of  adjvex
       e->next=G->adjlist[i].firstedge;
       G->adjlist[i].firstedge=e;
       e=(EdgeNode*)malloc(sizeof(EdgeNode));
       e->adjvex=i;
       e->next=G->adjlist[j].firstedge;
       G->adjlist[j].firstedge=e;
   }
}
typedef  int boollean;
boollean  visited[maxvertex];

/*Depth recursive algorithm of adjacency list*/
void  DFS(GraphAdjlist GL,int i){
   EdgeNode *p;
   visited[i]=1;
   cout<<GL.adjlist[i].data<<" ";
   p=GL.adjlist[i].firstedge;
   while(p){
       if(!visited[p->adjvex]){
           DFS(GL,p->adjvex);
       }
       p=p->next;
   }
}
/*print  the  asjacency list*/
void DFSTraverse(GraphAdjlist GL){
    int i;
    for(int i=0;i<GL.numvertex;i++){
        visited[i]=0;
    }
    for(i=0;i<GL.numvertex;i++){
        if(!visited[i])
            DFS(GL,i);
    }
}
int main()
{
    GraphAdjlist  *G=new GraphAdjlist;
    CreateALGrapha(G);
    DFSTraverse(*G);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值