Path in Matrix


Given a N X N  matrix Matrix[N][N] of positive integers.  There are only three possible moves from a cell Matrix[r][c].

1. Matrix[r+1][c]

2. Matrix[r+1][c-1]

3. Matrix[r+1][c+1]

Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.

Input:
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the order of matrix. Next line contains N*N integers denoting the elements of the matrix in row-major form.

Output:

Output the largest sum of any of the paths starting from any cell of row 0 to any cell of row N-1. Print the output of each test case in a new line.

Constraints:

1<=T<=20
2<=N<=20
1<=Matrix[i][j]<=1000 (for all 1<=i<=N && 1<=j<=N)

Example:

Input:
1
2
348 391 618 193

Output:
1009

Explanation: In the sample test case, the path leading to maximum possible sum is 391->618.  (391 + 618 = 1009)

**For More Examples Use Expected Output**

基本动规


代码:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
	public static void main (String[] args)
    {
        //code
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        int[] inputArray = new int[number];
        int[] result = new int[number];
        for(int i=0;i<number;i++){
            int n = input.nextInt();
            int [][] matrix = new int[n][n];
            for(int x=0;x<matrix.length;x++){
                for(int y = 0;y<matrix.length;y++){
                    matrix[x][y] = input.nextInt();
                }
            }
            result[i] = compute(matrix);
        }
        for(int i=0;i<result.length;i++){
            System.out.println(result[i]);
        }
    }

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

        for(int i=1;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++){
                int left=Integer.MIN_VALUE, right=Integer.MIN_VALUE, top= matrix[i-1][j];
                if(j>0) left = matrix[i-1][j-1];
                if(j<matrix[0].length-1) right  = matrix[i-1][j+1];

                matrix[i][j] += Math.max(left, Math.max(right, top));
            }
        }
        int max = Integer.MIN_VALUE;
        for(int lastRow: matrix[matrix.length-1]){
            max = Math.max(max, lastRow);
        }
        return max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值