矩阵最优路径

Given an NxM (N rows and M columns) integer matrix with non-negative values (0..MAX_INT inclusive).

What is the maximum sum from going top left (0, 0) to bottom right (N-1, M-1) ?

The condition is that when you're at point (p, q), you can only move to either right (p, q+1) or down (p+1, q).

Expected time complexity O(N*M)
Expected space complexity O(N+M) 


Ans:DP strategy.


about space complexity, need elaborate on it.


package com.zhuyu_deng.test;


public class Test
{
    public static void main(String args[])
    {
         int x[][] = { {1,2,3,4},
         {12,13,14,5},
         {11,16,15,6},
         {10,9,8,7},
         };
         System.out.println(findOptPath2(x));
    }

    private static int findOptPath(int[][] x)
    {
        int d[][] = new int[x.length][x[0].length];
        
        d[0][0] = x[0][0];
        for (int i = 1; i < x.length; ++i)
            d[i][0] = d[i-1][0] + x[i][0];
        for (int i = 1; i < x[0].length; ++i)
            d[0][i] = d[0][i-1] + x[i][0];
        
        for (int i = 1; i < x.length; ++i)
        {
            for (int j = 1; j < x[0].length; ++j)
            {
                if (d[i-1][j] > d[i][j-1])
                    d[i][j] = d[i-1][j] + x[i][j];
                else
                    d[i][j] = d[i][j-1] + x[i][j];
            }
        }
        return d[x.length-1][x[0].length-1];
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值