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 <bits/stdc++.h>
#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;
vector<int>adj[10005];
int dis[100005]={0};
bool vis[100005];
void bfs(int s)
{
    queue<int>q;
    dis[1]=0;
    q.push(s);

    while(!q.empty())
    {
      int top=q.front();
      q.pop();
    for(int i=0;i<adj[top].size();++i)
    {

        if(vis[adj[top][i]]==false) {
           dis[adj[top][i]]=dis[top]+1;
            vis[adj[top][i]]=true;
            q.push(adj[top][i]);
        }
    }
    }
}

int main()
{
    int t;
    cin>>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<m;++i){
            cin>>u>>v;
        adj[u].pb(v);
        adj[v].pb(u);
        }
        bfs(1);
        cout<<dis[n]<<endl;
    }
    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值