-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGold Mine Problem .txt
75 lines (73 loc) · 1.92 KB
/
Gold Mine Problem .txt
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb=new StringBuffer();
int T=Integer.parseInt(br.readLine());
while(T-->0)
{
String[] s=br.readLine().split("\\s");
int m=Integer.parseInt(s[0]);
int n=Integer.parseInt(s[1]);
s=br.readLine().split("\\s");
int[][] arr=new int[m][n];
int[][] dp=new int[m+1][n+1];
int count=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=Integer.parseInt(s[count++]);
}
}
for(int i=0;i<m+1;i++)
{
for(int j=0;j<n+1;j++)
{
dp[i][j]=-1;
}
}
int ans=0;
for(int i=0;i<m;i++)
{
ans=Math.max(ans,maxgold(arr,m,n,i,0,dp));
}
sb.append(ans+"\n");
}
System.out.print(sb);
}
public static int maxgold(int[][] arr,int m,int n,int posx,int posy,int[][] dp)
{
if(dp[posx][posy]!=-1)
{
return dp[posx][posy];
}
if(posy==n-1)
{
return dp[posx][posy]=arr[posx][posy];
}
int smallans1,smallans2,smallans3;
smallans1=smallans2=smallans3=arr[posx][posy];
if(canplace(m,n,posx,posy+1))
{
smallans1+=maxgold(arr,m,n,posx,posy+1,dp);
}
if(canplace(m,n,posx-1,posy+1))
{
smallans2+=maxgold(arr,m,n,posx-1,posy+1,dp);
}
if(canplace(m,n,posx+1,posy+1))
{
smallans3+=maxgold(arr,m,n,posx+1,posy+1,dp);
}
return dp[posx][posy]=Math.max(smallans1,Math.max(smallans2,smallans3));
}
public static boolean canplace(int m,int n,int posx,int posy)
{
return posx>=0 && posy>=0 && posx<m && posy<n;
}
}