I m trying a recursive approach for magic grid problem( AMR11A ) but getting wrong anser plz help me in my approach and correct if possible plz
here is my code
/* package whatever; // don’t place package name! */
import java.util.;
import java.lang.;
import java.io.*;
/* Name of the class has to be “Main” only if the class is public. */
class Ideone
{public static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scn = new FastReader();
int t=scn.nextInt();
while(t>0){
int m=scn.nextInt();
int n=scn.nextInt();
int[][] a=new int[m][n];
int [][] dp=new int[m][n];
for(int i=0;i<dp.length;i++) {
Arrays.fill(dp[i], 0);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a[i][j]=scn.nextInt();
}
}
System.out.println(magic_grid(a,0,0,m-1,n-1,dp));
t--;
}
}
public static int magic_grid(int[][] a,int si,int sj,int m,int n,int[][] dp) {
if((si==m&&sj==n-1)||(si==m-1&&sj==n)) {
return 1;
}
if(si>m-1||sj>n-1) {
return Integer.MAX_VALUE;
}
if(dp[si][sj]!=0){
return dp[si][sj];
}
int o1=magic_grid(a, si+1, sj, m, n,dp)-a[si+1][sj];
int o2=magic_grid(a, si, sj+1, m, n,dp)-a[si][sj+1];
int r= Math.min(o1, o2);
if(r<1) {
dp[si][sj]=1;
return 1;
}
dp[si][sj]=r;
return r;
}
}