Elements of Programming in Java
Problem 16.3 - Count the number of ways to traverse a 2D array.
Variant 3: A fisherman is in a rectangular sea. The value at the fish at point (i,j) in the sea is specified by an nxm matrix. Write a program that computes the maximum value of fish a fisherman can catch on a path from the upper leftmost to lower rightmost points. The fisherman can only move right or down.
My initial approach was recursive. Recursively see all valid paths and sum all the values of fish along the path. Once the fisherman reaches top left (starting from bottom right), add the sum to a list and later extract maximum from the list to display the answer. The code below implements this algorithm.
//calculate max fish caught in grid
public static int maxFishInGrid(int[][] sea) {
int maxFish = 0;
ArrayList<Integer> result = new ArrayList<>();
computeFish(sea, sea.length-1, sea[0].length-1, 0, result);
for(int a: result) {
maxFish = Math.max(maxFish, a);
}
return maxFish;
}
private static void computeFish(int[][] sea, int i, int j, int sum, ArrayList<Integer> result) {
if(i == 0 && j == 0) {
result.add(sum+sea[i][j]);
return;
}
sum += sea[i][j];
if(i > 0 ) {
computeFish(sea, i-1, j, sum, result);
}
if(j > 0) {
computeFish(sea, i, j-1, sum, result);
}
}
My question is how can I memoize the results to make this a DP solution.