fork download
  1. #include <bits/stdc++.h>
  2. #define pii pair<int,int>
  3. #define endl cout<<"\n";
  4. #define fi first
  5. #define int long long
  6. #define se second
  7. #define ios ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
  8. #define op freopen
  9. #define TXT "test"
  10. #define freo if(fopen(TXT".inp","r")){op(TXT".inp","r",stdin);op(TXT".out","w",stdout);}
  11.  
  12. using namespace std;
  13. int n,m;
  14. bool a[1005][1005];
  15. bool vs[1005][1005];
  16. int u1,v1,u2,v2,d[1005][1005];
  17. int dx[]={0,0,1,-1};
  18. int dy[]={1,-1,0,0};
  19. void bfs(pii i1,pii i2)
  20. {
  21. queue<pii> q;
  22. vs[i1.fi][i1.se]=1;
  23. q.push(i1);
  24. pii c;
  25. int x,y,ox,oy;
  26. while(!q.empty())
  27. {
  28. c=q.front();
  29. q.pop();
  30. x=c.fi;
  31. y=c.se;
  32. for(int i=0;i<4;i++)
  33. {
  34. ox=dx[i]+x;
  35. oy=dy[i]+y;
  36. if(!vs[ox][oy]&&ox>=1&&ox<=n&&oy>=1&&oy<=m&& a[ox][oy]==0 )
  37. {
  38. vs[ox][oy]=1;
  39. q.push({ox,oy});
  40. d[ox][oy]=d[x][y]+1;
  41. }
  42. }
  43. }
  44. }
  45. main()
  46. {
  47. ios;
  48. freo;
  49. cin>>n>>m;
  50. for(int i=1;i<=n;i++)
  51. {
  52. for(int j=1;j<=m;j++)
  53. {
  54. cin>>a[i][j];
  55. }
  56. }
  57. cin>>u1>>v1>>u2>>v2;
  58. for(int i=0;i<=n;i++)
  59. vs[i][0]=1;
  60. for(int i=0;i<=m;i++)
  61. vs[0][i]=1;
  62. d[u1][v1]=1;
  63. bfs({u1,v1},{u2,v2});
  64. if(!vs[u2][v2])
  65. {
  66. cout<<-1;
  67. }
  68. else
  69. {
  70. cout<<d[u2][v2];
  71. }
  72. }
Success #stdin #stdout 0s 5672KB
stdin
Standard input is empty
stdout
1