非递归dfs算法

#include <stdio.h>
  #include <malloc.h>
  #include <stdlib.h>
  #define MAXSIZE 100
  typedef char InfoType;
  typedef char vertex;
  typedef struct ANode //定义弧类型
  {
  int adjvex;
  struct ANode *nextarc;
  InfoType Info;
  }ArcNode;
  typedef struct //定义顶点类型
  {
  vertex data;
  ArcNode *fistarc;
  }VertexNode;
  typedef struct //定义图类型
  {
  VertexNode adjlist[MAXSIZE]; //邻接表
  int n,e;
  }ALGraph;
  void CreateALGraph(ALGraph *&g,int array[][MAXSIZE],int k) //传递一个邻接矩阵创建图
  {
  g=(ALGraph *)malloc(sizeof(ALGraph));
  for(int i=0;i<k;i++)
  g->adjlist[i].fistarc=NULL;
  int cnt=0;
  ArcNode *p;
  for(int i=0;i<k;i++)
  for(int j=0;j<k;j++)
  if(array[i][j]!=0)
  { 
  cnt++;
  p=(ArcNode *)malloc(sizeof(ArcNode));
  p->adjvex=j;
  p->nextarc=g->adjlist[i].fistarc;
  g->adjlist[i].fistarc=p;
  }
  g->n=k;g->e=cnt;
  }
  void dfs(ALGraph *g,int v,int visited[],int _vertex[]) //dfs()
  {
  int _v,i=0; //_v为初始顶点v的邻接点
  ArcNode *p;
  _vertex[0]=v; //保存顶点的数组
  visited[v]=1; //标记顶点是否已访问的数组
  p=g->adjlist[v].fistarc; //p为顶点v的第一条边
  while(p!=NULL)
  {
  _v=p->adjvex;
  if(visited[_v]==0) //如果该顶点未访问过
  {
  i++;
  _vertex[i]=_v;
  visited[_v]=1;
  p=g->adjlist[_v].fistarc; //从下一个未访问过的顶点开始深度优先遍历
  }
  else //否则找下一个相领顶点
  p=p->nextarc;
  }
  for(int j=0;j<=i;j++) //打印出_vertex数组中的内容,即连通图的所有顶点 
  printf("%d ",_vertex[j]);
  printf("\n");
  }
  int main() //主函数调用
  {
  int graph_array[ ][MAXSIZE]={
  {0,1,0,1,1},
  {1,0,1,1,0},
  {0,1,0,1,1},
  {1,1,1,0,1},
  {1,0,1,1,0}
  };
  ALGraph *g;
  CreateALGraph(g,graph_array,5);
  int visited[MAXSIZE]={0};
  int _vertex[MAXSIZE]={0};
  dfs(g,2,visited,_vertex);
  system("pause");
  return 0;
  }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值