Java - Maximum sum in path through a 2D array

前端 未结 3 1010
谎友^
谎友^ 2020-12-08 06:05

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) h

3条回答
  •  时光说笑
    2020-12-08 06:22

    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));
    }
    

提交回复
热议问题