-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMaximum path sum in matrix.java
57 lines (51 loc) · 1.44 KB
/
Maximum path sum in matrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// { Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while(t-- > 0){
int N = Integer.parseInt(in.readLine());
String input_line[] = in.readLine().trim().split("\\s+");
int Matrix[][] = new int[N][N];
for(int i = 0; i < N*N; i++)
Matrix[(i/N)][i%N] = Integer.parseInt(input_line[i]);
Solution ob = new Solution();
System.out.println(ob.maximumPath(N, Matrix));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution{
static int maximumPath(int n, int matrix[][])
{
// code here
int [][]dp = new int [n][n];
for(int i=0;i<n;i++)
{
dp[0][i] = matrix[0][i];
}
int u,l,r;
for(int i=1;i<n;i++)
{
for(int j =0;j<n;j++)
{
u = dp[i-1][j];
l = j-1>=0 ? dp[i-1][j-1] : 0;
r = j+1<n ? dp[i-1][j+1] : 0;
dp[i][j] = matrix[i][j] + Math.max(u, Math.max(l,r));
}
}
int max = -1;
for(int i=0;i<n;i++)
{
max = Math.max(dp[n-1][i],max);
}
return max;
}
}