AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
const int maxn=1e6+5;
const int inf=0x3f3f3f3f;
int dis[maxn],mp[1005][1005],n,m;
int spfa(int flag){queue<int>q;memset(dis,-1,sizeof(dis));dis[1]=0;q.push(1);while(!q.empty()){int u=q.front();q.pop();for(int i=1;i<=n;i++){if(mp[u][i]==flag&&dis[i]==-1){dis[i]=dis[u]+1;q.push(i); }}} return dis[n];
}
main(){cin>>n>>m;for(int i=1;i<=m;i++){int x,y;cin>>x>>y;mp[x][y]=mp[y][x]=1;}cout<<spfa(1-mp[1][n])<<endl;
}