ann8497

frogJump Samsung

Aug 22nd, 2019
1,459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. /*
  2. this is a mix of dfs with dp
  3. */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. int n,m;
  9. int a[100][100];
  10.  
  11. int r[] = {0, -1, 0, 1};
  12. int c[] = {-1, 0, 1, 0};
  13.  
  14. int dp[100][100];
  15.  
  16. bool valid(int x, int y){
  17.     return (x>0 && x<=n && y>0 && y<=m && a[x][y] == 1);
  18. }
  19.  
  20. void solve(int sx, int sy, int dx, int dy, int ans){
  21.    
  22.    /*
  23.     the below statement is written to avoid unnecessary calls of recursion
  24.     for example there are 2 paths a->b->c and e->b->c;
  25.     now in path and path 2 b is present in both
  26.     suppose a->b cost is less than e->b then there is no point to call further recursion from
  27.     path 2
  28.     here local minimum leads to global minimum
  29.    */
  30.  
  31.     if(dp[sx][sy] > ans){
  32.     dp[sx][sy] = ans;
  33.    
  34.     for(int i = 0; i<4; i++){
  35.        
  36.         int x = sx + r[i];
  37.         int y = sy + c[i];
  38.        
  39.         if(valid(x, y)){
  40.            int temp;
  41.            if(y == sy)temp = 1;
  42.            if(x == sx)temp = 0;
  43.            solve(x,y,dx,dy,ans+temp);
  44.         }
  45.     }
  46.    }
  47.    
  48. }
  49.  
  50. int main(){
  51.    
  52.     cin>>n>>m;
  53.     for(int i = 1; i<=n; i++){
  54.         for(int j = 1; j<=m; j++){
  55.            dp[i][j] = 1000000;
  56.            cin>>a[i][j];
  57.         }
  58.     }    
  59.  
  60.     int sx,sy,dx,dy;    
  61.     cin>>sx>>sy>>dx>>dy;
  62.    
  63.     solve(sx, sy, dx, dy, 0);
  64.    
  65.     cout<<dp[dx][dy]<<endl;
  66.    
  67.     return 0;
  68. }
Add Comment
Please, Sign In to add comment