fork(1) download
  1. #include <iostream>
  2. #include <queue>
  3. #define MAX 110
  4. using namespace std;
  5. typedef pair<int,int> pii;
  6.  
  7. int dx[8]={-1,-1,-1,0,0,1,1,1},dy[8]={1,0,-1,1,-1,1,0,-1},dist[MAX][MAX];
  8. bool g[MAX][MAX],visited[MAX][MAX];
  9. int bfs(const int start,const int end){
  10. queue<pii>q;
  11. size_t i;
  12. int nowx,nowy,nextx,nexty;
  13. q.push(pii(start,start));
  14. while(!q.empty()){
  15. nowy=q.front().first;
  16. nowx=q.front().second;
  17. q.pop();
  18. if(nowy==end||nowx==end) return dist[nowy][nowx];
  19. visited[nowy][nowx]=true;
  20. for(i=0;i<8;++i){
  21. nexty=nowy+dy[i];
  22. nextx=nowx+dx[i];
  23. if(!visited[nexty][nextx]) continue;
  24. else if(g[nexty][nextx]) dist[nexty][nextx]=dist[nowy][nowx]+1;
  25. q.push(pii(nexty,nextx));
  26. }
  27. }
  28. return -1;
  29. }
  30. int main(void){
  31. ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
  32. int n,x,y,m,a,b;
  33. cin>>n>>x>>y>>m;
  34. while(m--){
  35. cin>>a>>b;
  36. g[a][b]=g[b][a]=true;
  37. }
  38. cout<<bfs(x,y)<<'\n';
  39. return 0;
  40. }
Success #stdin #stdout 0s 4332KB
stdin
9
7 3
7
1 2
1 3
2 7
2 8
2 9
4 5
4 6
stdout
-1