王道考研 ++++ 图的深度优先搜索

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MaxSize 100

typedef struct EageTable  //边表
{
  int eageData;           //值
  struct EageTable *next; //指向下一条弧
}EageTable;
typedef struct HeadTable  //头表
{
  int headData;           //值
  EageTable *first;       //指向头节点后第一个节点
}HeadTable,HeadList[MaxSize];
typedef struct{
  HeadList Graph;
  int headNum,arcNum;     //头节点书 弧数
}Graph;
bool vis[MaxSize] = {false};

void InitGraph(Graph *G);
void CreateGraph(Graph *G,int flag,int a,int b);
void DFS(Graph *G,int front);
void TraverDFS(Graph *G);

/*初始化邻接表的头*/
void InitGraph(Graph *G)
{
  int i;
  for(i = 1;i <= G->headNum;i++)
  {
    G->Graph[i].headData = i;
    G->Graph[i].first = NULL;
  }
}
/*创建邻接表*/
void CreateGraph(Graph *G,int flag,int a,int b)
{
  EageTable* eage;
  eage = (EageTable*)malloc(sizeof(EageTable));
  eage->eageData = b;
  //头插入
  eage->next = G->Graph[a].first;
  G->Graph[a].first = eage;
  //图为无向图时
  if(flag == 2)
  {
    EageTable* eagee;
    eagee = (EageTable*)malloc(sizeof(EageTable));
    eagee->eageData = a;
    //头插入
    eagee->next = G->Graph[b].first;
    G->Graph[b].first = eagee;
  }
}
/*深搜*/
void DFS(Graph *G,int front)
{
  vis[front] = true;//标志节点已读
  printf("%-2d",front);
  EageTable *eage = G->Graph[front].first;//eage区front节点的侧表

  while (eage)
  {
    if(!vis[eage->eageData])DFS(G,eage->eageData);
    eage = eage->next;
  }
}
void TraverDFS(Graph *G)
{
  int i;

  for(i = 1;i <= G->headNum;i++)
  {
    if(!vis[i])DFS(G,i);
  }
}
int main(int argc, char const *argv[]) {
  Graph G;
  int i,flag,start;

  printf("有向图输入1,无向图输入2:");
  scanf("%d",&flag);
  printf("请输入节点数:");
  scanf("%d",&G.headNum);
  InitGraph(&G);
  printf("请输入弧的条数(从1开始):");
  scanf("%d",&G.arcNum);
  printf("请输%d入条边:\n",G.arcNum);
  for(i = 0;i < G.arcNum;i++)
  {
    int a,b;
    scanf("%d %d",&a,&b);
    CreateGraph(&G,flag,a,b);
  }
  printf("DFS结果:\n");
  TraverDFS(&G);
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值