矩阵最优路径


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) 



about space complexity, need elaborate on it.





package com.zhuyu_deng.test;



public class Test
{
	private static int findOptPath(int[][] a)
	{
		int d[][] = new int[a.length][a[0].length];
		int m = a.length;
		int n = a[0].length;
		
		d[0][0] = a[0][0];
		for (int i = 1; i < m; ++i)
			d[i][0] = d[i - 1][0] + a[i][0];
		for (int j = 1; j < n; ++j)
			d[0][j] = d[0][j - 1] + a[0][j];
		
		for (int i = 1; i < m; ++i)
		{
			for (int j = 1; j < n; ++j)
			{

				if (d[i-1][j] > d[i][j-1])
					d[i][j] = a[i][j] + d[i-1][j];
				else
					d[i][j] = a[i][j] + d[i][j-1];
			}
		}
		
		for (int i = 0; i < m; ++i)
		{
			for (int j = 0; j < n; ++j)
				System.out.print(a[i][j] + "  ");
			System.out.println();
		}
		System.out.println();
		
		for (int i = 0; i < m; ++i)
		{
			for (int j = 0; j < n; ++j)
				System.out.print(d[i][j] + "  ");
			System.out.println();
		}
		return d[m - 1][n - 1];
	}

	public static void main(String args[])
	{
		// int[] a = {-2,11,-4,13,-5,-2};
		int[][] b = { { 0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 },
				{ -1, 8, 0, -2 } };
		int [][] matrix = 
			{	{2,3,4,1},
				{1,1,3,9},
				{2,2,3,1},
				{2,2,3,1}
			};
		System.out.println(findOptPath(matrix));
	}
}


原文地址:https://www.cnblogs.com/snake-hand/p/3181908.html