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 T. T testcases follow.
First line of each test case contains two space-separated integers N, M.
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 ≤ X, Y ≤ N
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;
}