Reachability (BFS basic exercises)

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem 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 Sentinel Pass and through the relevant channels. 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 groups, 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 No. 1 on the pass, then the output YES, otherwise output NO.

Sample Input
2 1
1 2
2 1
2 1
Sample Output
NO
YES

#include <string.h>
#include <stdio.h>
#include<queue>
using namespace std;
int bian[1001][1001],vis[1001],n;
void BFS(int n)
{
    queue<int >q;
    q.push(n);
    while(!q.empty())
    {
        int t=q.front();
        q.pop();
        for(int i=1;i<n;i++)
        {
            if(!vis[i]&&bian[t][i])
            {
                vis[i]=1;
                q.push(i);
            }
        }
    }

}
int main()
{
int m,a,b;
while(cin>>n>>m)
{
    memset(vis,0,sizeof(vis));
    memset(bian,0,sizeof(bian));
    for(int i=0;i<m;i++)
    {
        cin>>a>>b;
        bian[a][b]=1;
    }
    vis[n]=1;
    BFS(n);
    if(vis[1]==1)
        printf("YES\n");
    else
        printf("NO\n");
}

return 0;
}

Guess you like

Origin blog.csdn.net/dongjian2/article/details/90183809