Advertisement
leonardo_aly7

csr4

Jan 30th, 2012
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1.  
  2. public class csr4 {
  3.  
  4.     /**
  5.      *  csr4: given 2D array of integers (possibly negative) ,
  6.      *  you start from cell (0,0)  and stop at cell (h-1,w-1)
  7.      *  where h and w are height and width and each cell can't be visited more than 1 time.
  8.      *  you add the integer in each cell you visit to your Current Sum ,
  9.      *  find the maximum possible sum.
  10.      */
  11.  
  12.     static int [][] map =  {{  2,  3, 40,  5, 2},
  13.                             {  4, 54,  6,  8, 0},
  14.                             {  8,  6,  5,  3, 0},
  15.                             { 34, 65,  8, 66, 9},
  16.                             { 44,  6,  7, 23, 1}};
  17.  
  18.    
  19.     public static int solve(int i, int j) {
  20.  
  21.         if (i >= map.length || j >= map[0].length) {
  22.             return -1;
  23.            
  24.         } else if (i == map.length && j == map[0].length) {
  25.             return map[i][j];
  26.         } else {
  27.             return map[i][j] + Math.max(solve(i + 1, j),solve(i, j + 1));
  28.         }
  29.     }
  30.  
  31.    
  32.     public static int solveDP(){
  33.         int a[][] = new int[map.length][map[0].length];
  34.         for (int i = a.length-1 ; i >= 0; i--) {
  35.             for (int j = a[0].length-1 ; j >= 0; j--) {
  36.                 if (i==map.length-1 || j==map[0].length-1)
  37.                     a[i][j] = map[i][j];
  38.                 else a[i][j] = map [i][j] + Math.max(a[i][j+1], a[i+1][j]);
  39.             }
  40.         }
  41.        
  42.         return a[0][0];
  43.     }
  44.     public static void main(String[] args) {
  45.  
  46.         int a = solve(0, 0);
  47.         System.out.println("REC SOLUTION : " + a);
  48.         System.out.println("DP  SOLUTION : "+solveDP());
  49.  
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement