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

 题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2139

  裸BFS。

 

 1 #include <stdio.h>

 2 #include <string.h>

 3 int p[1001][1001],o[1001],k[1001];

 4 int bfs(int n)

 5 {

 6     int i,j,start,end,a,num = 1;

 7     start = end = 0;

 8     while(start <= end)

 9     {

10        a = 1;

11        for(i = start;i <= end;i ++)

12        {

13           for(j = 1;j <= n;j ++)

14           {

15               if(p[k[i]][j] == 1 && o[j]!=1)

16               {

17                   k[end+a] = j;

18                   o[j] = 1;

19                   a ++;

20               }

21           }

22        }

23        start = end + 1;

24        end =end + a -1;

25        for(i = start;i <= end;i ++)

26        {

27            if(k[i] == 1)

28            {

29                return num;

30            }

31        }

32        num ++;

33     }

34     return 0;

35 }

36 int main()

37 {

38     int i,n,m,a,b;

39     while(scanf("%d%d",&n,&m)!=EOF)

40     {

41         memset(k,0,sizeof(k));

42         memset(p,0,sizeof(p));

43         memset(o,0,sizeof(o));

44         for(i = 1;i <= m;i ++)

45         {

46             scanf("%d%d",&a,&b);

47             p[a][b] = 1;

48         }

49         k[0] = n;o[n] = 1;

50         i = bfs(n);

51         if(i == 0)

52         printf("NO\n");

53         else

54         printf("%d\n",i);

55     }

56     return 0;

57 }

 

你可能感兴趣的:(bfs)