9

Basically I have a problem that goes something similar to this:

There is a garden of strawberry plants represented by a 2D, square array. Each plant(each element) has a number of strawberries. You start at the top left corner of the array, and you can only move to the right or down. I need to design a recursive method to calculate the paths through the garden and then output which one yields the most strawberries.

I think I have an understanding of really really simple recursion problems, but this problem has gone way over my head. I'm not really sure where to start or where to go as far as creating a recursive method.

Any help related to the code or helping me understand the concept behind this problem is greatly appreciated. Thanks.

user1547050
  • 337
  • 2
  • 7
  • 15

3 Answers3

15

Like dasblinkenlight said, the most efficient way to do this is using a memoization or dynamic programming technique. I tend to prefer dynamic programming, but I'll use pure recursion here.

The answer centers around the answer to one fundamental question: "If I'm in the square in row r and column c on my field, how can I evaluate the path from the top left to here such that the number of strawberries is maximized?"

The key to realize is that there's only two ways to get in the plot in row r and column c: either I can get there from above, using the plot in row r-1 and column c, or I can get there from the side, using the plot in row r and column c-1. After that, you just need to make sure you know your base cases...which means, fundamentally, my purely recursive version would be something like:

int[][] field;    
int max(int r, int c) {
    //Base case
    if (r == 0 && c == 0) {
        return field[r][c];
    }
    //Assuming a positive number of strawberries in each plot, otherwise this needs
    //to be negative infinity
    int maxTop = -1, maxLeft = -1;
    //We can't come from the top if we're in the top row
    if (r != 0) {
        maxTop = field[r-1][c];
    }
    //Similarly, we can't come from the left if we're in the left column
    if (c != 0) {
        maxLeft = field[r][c-1];
    }
    //Take whichever gives you more and return..
    return Math.max(maxTop, maxLeft) + field[r][c];
}

Call max(r-1, c-1) to get your answer. Notice there's a lot of inefficiency here; you'll do much better by using dynamic programming (which I'll provide below) or memoization (which has already been defined). The thing to remember, though, is that both the DP and memoization techniques are simply more efficient ways that come from the recursive principles used here.

DP:

int maxValue(int[][] field) {
    int r = field.length;
    int c = field[0].length;
    int[][] maxValues = new int[r][c];
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            if (i == 0 && j == 0) {
                maxValues[i][j] = field[i][j];
            } else if (i == 0) {
                maxValues[i][j] = maxValues[i][j-1] + field[i][j];
            } else if (j == 0) {
                maxValues[i][j] = maxValues[i-1][j] + field[i][j];
            } else {
                maxValues[i][j] = Math.max(maxValues[i][j-1], maxValues[i-1][j]) + field[i][j];
            }
        }
    }
    return maxValues[r-1][c-1];
}

In both cases, if you want to recreate the actual path, just keep a 2D table of booleans that corresponds with "Did I come from above or to the left"? If the most strawberry path comes from above, put true, otherwise put false. That can allow you to retrace the patch after the calculation.

Notice that this is still recursive in principal: at each step, we're looking back at our previous results. We just happen to be caching our previous results so we don't waste a bunch of work, and we're attacking the subproblems in an intelligent order so that we can always solve them. For more on dynamic programming, see Wikipedia.

DivineWolfwood
  • 1,752
  • 12
  • 20
  • 2
    You probably meant `return maxValues[r-1][c-1];` – Quixotic Dec 08 '12 at 16:28
  • Hi DivineWolfwood, your example is very intersting. But, what is I would like to look both left and right? – Doro Apr 05 '14 at 17:07
  • Are you saying that you can go either left or right or down at every step? That's a completely different problem because it lets you repeat steps in places..I'd have to think through an algorithm for that. – DivineWolfwood Apr 10 '14 at 17:24
  • The Dynamic Programming approach works great, thanks! – ATP Feb 27 '15 at 05:32
  • Hey @DivineWolfwood I need help in similar question. How would you choose to traverse the 2D array, if you had to start from bottom left corner, and you can only move to the top or right based on the highest value present in your array. – NadZ Dec 20 '16 at 12:59
  • @NadZ I think the same thing should essentially suffice. You should start in the bottom left, at each step, you should examine the row below you and the row to your left (i.e. maxValues[i][j-1], maxValues[i+1][j]), and you should go across the row and go from bottom to top in rows. – DivineWolfwood Dec 21 '16 at 00:48
  • Hey @DivineWolfwood, can you help me with same but a **[bit complicated task](http://stackoverflow.com/q/42706957/2650174)**. – Anton Dozortsev Mar 09 '17 at 23:11
  • Sorry, I missed your question. @dasblinkenlight did a great job with his answer though :) – DivineWolfwood Apr 01 '17 at 06:23
5

You can do it using memoization. Here is Java-like pseudodoce (memo, R, and C are assumed to be instance variables available to the max method).

int R = 10, C = 20;
int memo[][] = new int[R][C];
for (int r=0 ; r != R ; r++)
    for (int c = 0 ; c != C ; c++)
        memo[r][c] = -1;
int res = max(0, 0, field);

int max(int r, int c, int[][] field) {
    if (memo[r][c] != -1) return memo[r][c];
    int down = 0; right = 0;
    if (r != R) down = max(r+1, c, field);
    if (c != C) right = max(r, c+1, field);
    return memo[r][c] = (field[r][c] + Math.max(down, right));
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You can solve this with DP tabulation method, with which you can save space from O(m*n) to just O(n). With DP Memorization, you need m*n matrix to store intermediate values. Following is my Python code. Hope it can help.

def max_path(field):
    dp = [sum(field[0][:i]) for i in range(1, len(field[0]) + 1)]
    for i in range(1, len(field)):
        for j in range(len(dp)):
            dp[j] = min(dp[j], dp[j - 1] if j > 0 else float('inf')) + field[i][j]
    return dp[-1]