bfs广度优先搜索经典模板题目

Monk and the Islands
Attempted by:  2720
/
Accuracy:  87%
/
Maximum Score:  20
/
 
48 Votes
Tag(s):
 

BFS, Easy, Graph Theory

PROBLEM
EDITORIAL
MY SUBMISSIONS
ANALYTICS

Monk visits the land of Islands. There are a total of N islands numbered from 1 to N. Some pairs of islands are connected to each other by Bidirectional bridges running over water.
Monk hates to cross these bridges as they require a lot of efforts. He is standing at Island #1 and wants to reach the Island #N. Find the minimum the number of bridges that he shall have to cross, if he takes the optimal route.

Input:
First line contains TT testcases follow.
First line of each test case contains two space-separated integers NM.
Each of the next M lines contains two space-separated integers X and Y , denoting that there is a bridge between Island X and Island Y.

Output:
Print the answer to each test case in a new line.

Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 104
1 ≤ M ≤ 105
1 ≤ XY ≤ N

SAMPLE INPUT
 
2
3 2
1 2
2 3
4 4
1 2
2 3
3 4
4 2
SAMPLE OUTPUT
 
2
2
Time Limit: 3.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit:

1024 KB

#include 
#define _ ios_base::sync_with_stdio(false);cin.tie(0);
using namespace std;
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define mp make_pair
#define all(a) a.begin(),a.end()
#define bitcnt(x) __builtin_popcountll(x)
#define MOD 1000000007
#define total 5000005
#define Me 1000000000001
#define NIL 0
#define MAXN 210005
#define EPS 1e-5
#define INF (1<<28)
#define pi 3.141593
int n,m,u,v;
int ans=0;
vectoradj[10005];
int dis[100005]={0};
bool vis[100005];
void bfs(int s)
{
    queueq;
    dis[1]=0;
    q.push(s);

    while(!q.empty())
    {
      int top=q.front();
      q.pop();
    for(int i=0;i>t;
    while(t--)
    {
        //int n,m,u,v;
        cin>>n>>m;
        memset(vis,false,sizeof(vis));
        memset(adj,0,sizeof(adj));
        for(int i=0;i>u>>v;
        adj[u].pb(v);
        adj[v].pb(u);
        }
        bfs(1);
        cout<


你可能感兴趣的:(BFS(),hackerearth)