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

来源:互联网 发布:windows arp 绑定 编辑:程序博客网 时间:2024/06/06 12:57

#include <stdio.h>#include <string.h>#include <queue>using namespace std;struct node      //用结构体来存储当前查找的点和到达这一点经过的步数{    int data;    int step;};int a[1005][1005], book[1005];int n, m;struct node v, t;void BFS(int x){    int i;    queue <node> Q;    //定义一个结构体队列    t.data = x;        //最开始查找的那一点,step为0    t.step = 0;    book[x] = 1;    Q.push(t);         //将这一点加入队列    while(!Q.empty())    {        v = Q.front();  //v记录下队首的值,v.data代表当前在查找的点        Q.pop();        //将队首出队        if(v.data == 1)        {            printf("%d\n", v.step);            return;        }        for(i = 1; i <= n; i++)     //从和v.data点有关的点开始依次查找        {            if(a[v.data][i] && !book[i])            {                t.data = i;                t.step = v.step + 1;  //步数加一继续循环,直到data值为1                Q.push(t);                book[i] = 1;            }        }    }    printf("NO\n");}int main(){    int u, v;    while(scanf("%d %d", &n, &m) != EOF)    {        memset(a, 0, sizeof(a));        memset(book, 0, sizeof(book));        while(m--)        {            scanf("%d %d", &u, &v);            a[u][v] = 1;        }        BFS(n);    }    return 0;}

阅读全文
0 0
原创粉丝点击