基于图的深度优先搜索策略(耿7.10)

 

Description

试基于图的深度优先搜索策略编写程序,判别以邻接表方式存储的有向图中,是否存在由顶点vi到vj的路径(i不等于j),

注意:程序中涉及的图的基本操作必须在此存储结构上实现。

 

 

Input

第一行输入有向图的顶点数n和边数m,用空格隔开;第二行输入顶点信息;分m行输入有向图边的信息,例如顶点对1,2表示从顶点1到顶点2的一条弧,最后一行输入待判别的顶点对vi,vj.(0<m,n<100)

 

 

Output

若有向图中存在由顶点vi到顶点vj的路径(i不等于j),则输出yes;否则输出no。

 

 

Sample Input

4 4

 

 

1 2 3 4

1 2

 

 

1 3

1 4

 

 

2 3

2 3

 

 

Sample Output

yes

 

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX_VERTEX_NUM 1000
typedef struct ArcNode{
     int adjvex;
     struct ArcNode *nextarc;
}ArcNode;

typedef struct VNode{
     int data;
     ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];

typedef struct{
     AdjList vertices;
     int vexnum,arcnum;
}ALGraph;

void CreatGraph(ALGraph *G)
{
   int i,j,k;
   ArcNode *p;
   scanf("%d%d",&G->vexnum,&G->arcnum);
   for(i=1;i<=G->vexnum;i++)
     {scanf("%d",&G->vertices[i].data);
      G->vertices[i].firstarc=NULL;
     }
   for(k=1;k<=G->arcnum;k++)
     {
        p=(ArcNode*)malloc(sizeof(ArcNode));
        scanf("%d%d", &i, &j);
        p->adjvex = j;/*弧的终点*/
        p->nextarc=G->vertices[i].firstarc;
        G->vertices[i].firstarc=p;
     }

}
int DFS(ALGraph G,int i,int j)
{
    int visited[MAX_VERTEX_NUM];
    visited[i]=1;
    ArcNode*p=G.vertices[i].firstarc;
    if(i==j)return 0;
    else
    {
    while(p!=NULL)
    {
        if(p->adjvex == j)
        return 1;
        if(!(visited[p->adjvex])&&DFS(G,p->adjvex,j))
        return 1;
        p = p->nextarc;
    }
    return 0;
    }
}
int main()
{
  ALGraph G;
  int i,j;
  CreatGraph(&G);
  scanf("%d%d",&i,&j);
  if(DFS(G,i,j))
  {
      printf("yes\n");
  }
  else printf("no\n");
  return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值