Code46 矩阵的最大路径和问题 2

213 阅读2分钟

题目描述

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

code

public class Code46 {
    // 从matrix左上角,走到右下角,过程中只能向右或者向下
    // 到达后,回来,过程中只能向左或者向上,沿途数字只能获得一遍
    // 返回,最大路径和
    public static int comeGoMaxPathSum(int[][] matrix) {
        return process(matrix, 0, 0, 0);
    }

    // matrix中,没有负数
    // A来到的位置是 Ar,Ac
    // B来到的位置是 Br, Ar + Ac - Br
    // A和B,一定迈出的步数,一样多,同步走的
    // 两人会共同到达右下角,返回两个人路径的最大累加和
    // 重要限制:来到同一个位置时,只获得一份
    public static int process(int[][] matrix, int Ar, int Ac, int Br) {
        int N = matrix.length;
        int M = matrix[0].length;
        if (Ar == N - 1 && Ac == M - 1) {
            return matrix[Ar][Ac];
        }
        // 还没到右下角

        // A 下 B 下
        // A 右 B 右
        // A 右 B 下
        int Bc = Ar + Ac - Br;
        // A 下 B 右
        int ADownBRight = -1;
        if (Ar + 1 < N && Bc + 1 < M) {
            ADownBRight = process(matrix, Ar + 1, Ac, Br);
        }
        int ADownBDown = -1;
        if (Ar + 1 < N && Br + 1 < N) {
            ADownBDown = process(matrix, Ar + 1, Ac, Br + 1);
        }

        int ARightBRight = -1;
        if (Ac + 1 < M && Bc + 1 < M) {
            ARightBRight = process(matrix, Ar, Ac + 1, Br);
        }
        int ARightBDown = -1;
        if (Ac + 1 < M && Br + 1 < N) {
            ARightBDown = process(matrix, Ar, Ac + 1, Br + 1);
        }
        int nextBest = Math.max(Math.max(ADownBRight, ADownBDown), Math.max(ARightBRight, ARightBDown));
        // A B
        if (Ar == Br) {
            return matrix[Ar][Ac] + nextBest;
        }
        // A 和 B,一定是不同位置
        return matrix[Ar][Ac] + matrix[Br][Bc] + nextBest;
    }

    public static void main(String[] args) {
        int[][] matrix = {
                { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 },
                { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
                { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
                { 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
                { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 } };

        System.out.println(comeGoMaxPathSum(matrix));
    }
}