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

来源:互联网 发布:网络布局要看什么书籍 编辑:程序博客网 时间:2024/06/04 20:14
#include<bits/stdc++.h>using namespace std;bool Map[1050][1050];struct node{    int x,s;};int bfs(int v){    bool vis[1050];    queue <struct node> Q;    memset(vis,false,sizeof(vis));    struct node t,k;    t.x=v;    t.s=0;    Q.push(t);    while(!Q.empty())    {        t=Q.front();        Q.pop();        int X=t.x,S=t.s;        if(X==1)            return S;        for(int i=1; i<=v; i++)            if(Map[X][i]&&!vis[i])            {                struct node k;                k.x=i;                k.s=S+1;                Q.push(k);                vis[i]=true;            }    }    return -1;}int main(){    int v,e;    while(~scanf("%d%d",&v,&e))    {        memset(Map,false,sizeof(Map));        for(int i=0; i<e; i++)        {            int v1,v2;            scanf("%d%d",&v1,&v2);            Map[v1][v2]=true;        }        int k=bfs(v);        if(k==-1)printf("NO\n");        else printf("%d\n",k);    }}

0 0
原创粉丝点击