图结构练习——BFS——从起始点到目标点的最短步数(bfs)

来源:互联网 发布:mac 屏幕睡眠时间 编辑:程序博客网 时间:2024/06/05 03:51

题目描述不敢发了,怕又说我打广告。。。

#include <stdio.h>#include <stdlib.h>struct node{    int x,c;}q[10005];int map[1005][1005];int v[10005];void bfs(int x){    int i,e=1,s=0;    struct node t,f;    t.x=x;    t.c=0;    q[0]=t;    while(s<e)    {        t=q[s++];        if(map[t.x][1]==1)        {            printf("%d\n",t.c+1);            return ;        }        for(i=x-1;i>=1;i--)        {            f.x=i;            if(!v[i]&&map[t.x][i]==1)            {                f.c=t.c+1;                q[e++]=f;                v[f.x]=1;            }        }    }    printf("NO\n");}int main(){   struct node *p;   int n,m,a,b;   while(~scanf("%d%d",&n,&m))   {       memset(v,0,sizeof(v));       memset(map,0,sizeof(map));       while(m--)       {           scanf("%d%d",&a,&b);           map[a][b]=1;       }       v[n]=1;       bfs(n);   }    return 0;}


 

0 0