算法_动态规划_矩阵路径最大和

来源:互联网 发布:怎么申请网站域名 编辑:程序博客网 时间:2024/05/16 00:47

题目描述:有一个m×n的矩阵,现要从左上角走到右下角,并且方向只能是向下或者向右,
现规定一条路径的权值为走此路径所经过的值的和。给定一个矩阵,请找出权值最大的一条
路径。
Example:
2 5 6
3 9 4
7 9 1
所找到的路径为2->5->9->9->1,权值为26。

import java.util.Scanner;/** * @author 翔 * */public class Main {    private static int m;    private static int n;    private static int[][] mat;    private static int[][] dp;    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner sc=new Scanner(System.in);        m=sc.nextInt();        n=sc.nextInt();        mat=new int[m][n];        dp=new int[m][n];        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                mat[i][j]=sc.nextInt();            }        }        dp[m-1][n-1]=mat[m-1][n-1];        for(int i=m-2;i>=0;i--){            dp[i][n-1]=mat[i][n-1]+dp[i+1][n-1];        }        for(int j=n-2;j>=0;j--){            dp[m-1][j]=mat[m-1][j]+dp[m-1][j+1];        }        int i=m-2;        int j=n-2;        while(true){            int tempI=i;            int tempJ=j;            for(tempI=i;tempI>=0;tempI--){                dp[tempI][tempJ]=mat[tempI][tempJ]+Math.max(dp[tempI][tempJ+1],dp[tempI+1][tempJ]);            }            tempI=i;            tempJ=j;            for(tempJ=i;tempJ>=0;tempJ--){                dp[tempI][tempJ]=mat[tempI][tempJ]+Math.max(dp[tempI][tempJ+1],dp[tempI+1][tempJ]);            }            if(i==0&&j==0){                break;            }            if(i!=0){                i--;            }            if(j!=0){                j--;            }           }        System.out.println(dp[0][0]);       }}
0 0