gelita

lattice paths

Feb 11th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.25 KB | None | 0 0
  1. class Result {
  2. ​
  3.     /*
  4.      * Complete the 'latticePaths' function below.
  5.      *
  6.      * The function is expected to return an INTEGER.
  7.      * The function accepts following parameters:
  8.      *  1. INTEGER m
  9.      *  2. INTEGER n
  10.      */
  11.    
  12.     private static int destM, destN;
  13.     private static HashMap<String, Integer> cache;
  14. ​
  15.     public static int latticePaths(int m, int n) {
  16.         //Top-down Approach with Pure Recursion
  17. //         //Base Cases
  18. //         //1. Origin reached
  19. //         if(m==0 && n==0) return 1;
  20.        
  21. //         //2. Out of bounds
  22. //         if(m==-1 || n==-1) return 0;
  23.        
  24. //         //Make recursive Calls
  25. //         int recurseUp = latticePaths(m-1, n);
  26. //         int recurseLeft = latticePaths(m, n-1);
  27.        
  28. //         //Return result
  29. //         return recurseUp + recurseLeft;
  30.        
  31.         //Bottom-up Approach with Helper Method Recursion with Memoized Cache
  32.         // destM = m;
  33.         // destN = n;
  34.         // cache = new HashMap<>();
  35.         // return helper(0,0);
  36.        
  37.         //Iterative Tabulation Approach
  38.         int[][] T = new int[m+1][n+1];
  39.        
  40.         T[0][0] = 1;
  41.         //Fill out top row of table
  42.         for(int row=1; row<=m; row++) {
  43.             T[row][0] = T[row-1][0];
  44.         }
  45.        
  46.         //Fill out left col of table
  47.         for(int col=1; col<=n; col++) {
  48.             T[0][col] = T[0][col-1];
  49.         }
  50.        
  51.         //Fill out rest of table
  52.         for(int row=1; row<=m; row++) {
  53.             for(int col=1; col<=n; col++){
  54.                 T[row][col] = T[row-1][col] + T[row][col-1];
  55.             }
  56.         }
  57.         return T[m][n];
  58.        
  59.     }
  60.    
  61.    
  62.     private static int helper(int m, int n) {
  63.         //Base Cases
  64.         //0. Check cache
  65.         String key = Integer.toString(m)+"_"+Integer.toString(n);
  66.         if(cache.containsKey(key)) return cache.get(key);
  67.        
  68.         //1. Destination reached
  69.         if(m==destM && n==destN) return 1;
  70.        
  71.         //2. Out of Bounds
  72.         if(m >destM || n >destN) return 0;
  73.        
  74.         //Recurse down rows or right columns
  75.         int count = helper(m+1, n) + helper(m, n+1);
  76.         cache.put(key, count);
  77.        
  78.         return count;
  79.     }
  80. ​
Add Comment
Please, Sign In to add comment