往返的最大路径和

链接

给定一个矩阵matrix,先从左上角开始,每一步只能往右或者往下走,走到右下角。然后从右下角出发,每一步只能往上或者往左走,再回到左上角。任何一个位置的数字,只能获得一遍。返回最大路径和。

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    private static final int[] DX = {1, 0};

    private static final int[] DY = {0, 1};


    private static int fun(int[][] matrix, int row1, int col1, int row2, int[][][] dp) {

        if (dp[row1][col1][row2] != -1) {
            return dp[row1][col1][row2];
        }

        if (row1 == matrix.length - 1 && col1 == matrix[0].length - 1) {
            dp[row1][col1][row2] = matrix[row1][col1];
            return matrix[row1][col1];
        }


        int ret = 0;

        int col2 = row1 + col1 - row2;
        for (int i = 0; i < 2; ++i) {
            for (int j = 0; j < 2; ++j) {
                int x1 = DX[i] + row1;
                int y1 = DY[i] + col1;
                int x2 = DX[j] + row2;
                int y2 = DY[j] + col2;

                if (x1 >= 0 && x1 < matrix.length && y1 >= 0 &&
                        y1 < matrix[0].length && x2 >= 0 && x2 < matrix.length && y2 >= 0 && y2 < matrix[0].length) {
                    ret = Math.max(ret, fun(matrix, x1, y1, x2, dp));
                }
            }
        }

        if (row1 == row2) {
            ret += matrix[row1][col1];
        } else {
            ret += matrix[row1][col1] + matrix[row2][col2];
        }

        dp[row1][col1][row2] = ret;

        return ret;

    }


    private static int solve(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }

        int[][][] dp = new int[matrix.length][matrix[0].length][matrix.length];

        for (int i = 0; i < dp.length; ++i) {
            for (int j = 0; j < dp[i].length; ++j) {
                Arrays.fill(dp[i][j], -1);
            }
        }

        return fun(matrix, 0, 0, 0, dp);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int m = in.nextInt();
            int[][] matrix = new int[n][m];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                    matrix[i][j] = in.nextInt();
                }
            }
            System.out.println(solve(matrix));
        }
    }
}
上一篇:集合


下一篇:Python学习笔记:pd.sort_values实现排序