gelita

lattice paths

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