基于图的广度优先搜索策略(耿7.11)

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
#define MAXSIZE 50
typedef struct
{
    int ele[MAXSIZE];
    int front;
    int rear;
}Queue;
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 InitQueue(Queue*Q)
{
    Q->front=Q->rear=0;
}
int EnQueue(Queue*Q,int x)
{
    if((Q->rear+1)%MAXSIZE==Q->front)
        return 0;
    Q->ele[Q->rear]=x;
    Q->rear=(Q->rear+1)%MAXSIZE;
    return 1;
}
int DeQueue(Queue *Q,int *x)
{
    if(Q->front==Q->rear)
    return 0;
    *x=Q->ele[Q->front];
    Q->front=(Q->front+1)%MAXSIZE;
    return 1;
}
int QueueEmpty(Queue Q)
{
    if(Q.front==Q.rear)
    return 1;
    else return 0;
}
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 BFS(ALGraph G, int i, int j)
{
    ArcNode *p;
    Queue Q;
    int e,k;
    InitQueue(&Q);
    EnQueue(&Q,i);
    int visited[MAX_VERTEX_NUM];
    while(!QueueEmpty(Q))//队列不为空时
        {
            DeQueue(&Q,&e);//队头元素出队并置为e
            visited[e] = 1;//标记被访问过的顶点
            p = G.vertices[e].firstarc;
            for(; p != NULL; p = p -> nextarc)
            {
                k = p -> adjvex;//当前弧所指向顶点的位置
                if(k == j)
                    return 1;
                else if(!visited[k])//当前顶点未被访问过
                EnQueue(&Q,k);
            }
        }
        return 0;
}
int main()
{
  ALGraph G;
  int i,j;
  CreatGraph(&G);
  scanf("%d%d",&i,&j);
  if(BFS(G,i,j))
  {
      printf("yes");
  }
  else printf("no");
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值