G - the experimental data on the structure of FIG five: minimum number (BFS) from the starting point to the target point step

Description

In the ancient legend of Warcraft, there are two corps, called a natural disaster, a man named Guards. In the area where they are, there are n Pass, numbered 1 ... n, some of the passes between channels is connected. Wherein Sentinel Pass No. 1, No. n Pass the scourge. One day, the leader of the Lich King Scourge decided to send troops to attack the Sentinel, Scourge of such a large force, and even fill the river across the river. But the Lich King did not want to pay unnecessary costs, he wanted to know under the premise does not build any channel, whether to attack troops can arrive by Sentinel Pass and its associated channel; if possible, a minimum number of channels to go through. Because of the relatively large value of n (n <= 1000), then the Lich King found a good programming = _ = you, you help him solve this problem, otherwise you'll eat become his magic. In order to save himself, and quickly think of ways it.

Input

Input comprising a plurality of sets, each format.

The first line contains two integers n, m (n representing a Pass, between the channels there are m Pass).

The following m lines contains two integers a, b; represents a departure from b has a passage to the pass (note: the channel is unidirectional).

Output

If the Scourge can not build any channel to reach the No. 1 Pass, then the output of the minimum number of channels through, otherwise the output NO.

Sample

Input

2 1
1 2
2 1
2 1
Output

NO
1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#include<queue>
using namespace std;
int Map[1100][1100],vis[1100];
int n,m;
struct node
{
    int step;
    int data;
}t,k;
int flag;
void bfs(int x)
{
    queue<node>q;
    vis[x] = 1;
    t.data = x;
    t.step = 0;
    q.push(t);
    while(!q.empty())
    {
        k = q.front();
        q.pop();
        if(k.data == 1)
        {
            flag = 1;
            printf("%d\n",k.step);
            return ;
        }
        for(int i=1;i<=n;i++)
        {
            if(!vis[i]&&Map[k.data][i])
            {
                vis[i] = 1;
                t.data = i;
                t.step = k.step+1;
                q.push(t);
            }
        }
    }
}
int main()
{
    int u,v;
    while(~scanf("%d %d",&n,&m))
    {
        memset(vis,0,sizeof(vis));
        memset(Map,0,sizeof(Map));
        flag = 0;
        for(int i=0;i<m;i++)
        {
            scanf("%d %d",&u,&v);
            Map[u][v] = 1;
        }
        bfs(n);
        if(flag==0)
            printf("NO\n");
    }
    return 0;
}


Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104883716