fork download
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. const int maxn = 505;
  5. int n,m;
  6. #define inRange(i,j) (i >= 1 and i <=n and j >= 1 and j <= m)
  7.  
  8. int mat[maxn][maxn],visited[maxn][maxn],level[maxn][maxn];
  9.  
  10. queue< pair<int,int> >Q;
  11.  
  12. void solve(int i,int j)
  13. {
  14. Q.push(make_pair(i,j));
  15.  
  16. while(!Q.empty()){
  17.  
  18. int node1 = Q.front().first;
  19. int node2 = Q.front().second;
  20.  
  21. Q.pop();
  22.  
  23. // positions it can go to.
  24.  
  25. int a[] = {0,-mat[node1][node2],0,mat[node1][node2]} , b[] = {-mat[node1][node2],0,mat[node1][node2],0};
  26.  
  27. for(int x = 0; x < 4; x++){
  28.  
  29. int temp1 = node1 + a[x];
  30. int temp2 = node2 + b[x];
  31.  
  32. if(inRange(temp1,temp2) and !visited[temp1][temp2]){
  33. visited[temp1][temp2] = 1;
  34. level[temp1][temp2] = level[node1][node2] + 1;
  35. Q.push(make_pair(temp1,temp2));
  36. }
  37. }
  38.  
  39. }
  40. }
  41.  
  42. int main()
  43. {
  44.  
  45. visited[1][1] = 1;
  46. cin>>n>>m;
  47.  
  48. for(int x = 1; x <= n; x++)
  49. for(int y = 1; y <=m; y++)
  50. cin>>mat[x][y];
  51.  
  52. solve(1,1);
  53.  
  54. (level[n][m] != 0)?cout<<level[n][m]<<endl:cout<<-1<<endl;
  55.  
  56. }
Success #stdin #stdout 0s 19056KB
stdin
Standard input is empty
stdout
-1