Problem
You are given a matrix. You need to print the sum of all the numbers in the rectangle which has as the top left corner and as the bottom right corner.
I'm using top down dynamic programming approach to solve this problem. see my code.
import java.util.*;
public class Matrixsum
{
static int dp[][] = new int[4][4]; // for debugging max size 1001,1001
static int findsum(int arr[][] , int i, int j)
{
if(i<1 || j < 1) return 0;
if(dp[i][j] != -1)
return dp[i][j];
else
dp[i][j] = findsum(arr,i-1,j)+findsum(arr,i,j-1)+findsum(arr,i-1,j-1)+arr[i][j];
return dp[i][j];
}
public static void main(String[] args)
{
for(int[] d:dp) Arrays.fill(d,-1);
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int arr[][] = new int[1001][1001];
for(int i=0;i<a;i++)
{
for (int j = 0; j < b; j++) {
arr[i][j] = sc.nextInt();
}
}
int q = sc.nextInt();
while(q-- > 0)
{
int i = sc.nextInt();
int j = sc.nextInt();
System.out.println(findsum(arr,i,j));
}
System.out.println(Arrays.deepToString(dp));
// dp = new int[1001][1001];
}
}
Input
3 3
1 2 3
4 5 6
7 8 9
2
3 3
2 3
Output
162
60
[[-1, -1, -1, -1], [-1, 5, 11, 11], [-1, 13, 38, 60], [-1, 13, 64, 162]]
Expected output
45
21
But this is throwing very random numbers when query is entered . I'm not getting what's I'm missing here. Can somebody help ?
Thanks ✌️
nsubmatrices that are disjoint. - Amongaleniandjare supposed to be. Are you trying to say you want to create a lookup table with all possible combinations of queries? You don't have enough memory for that. - Amongalen