Posts All Sub-Matrices Sum
Post
Cancel

All Sub-Matrices Sum

PROBLEM DESCRIPTION

Given a NxM 2-D matrix, the task to find the sum of all the submatrices.

geeksforgeeks

SOLUTION

snapshot

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
import java.io.*;

class GFG {
 
 public static int matrixSum(int[][] matrix){
     
     int n = matrix.length;
     int m = matrix[0].length;
    
     int totalSum = 0;
     
     for(int i=0; i<n; i++){
         
         for(int j=0; j<m; j++){
             
             int topLeft = (i+1) * (j+1);
             int bottomRight = (n-i) * (m-j);
             
             int times = topLeft * bottomRight;
             
             int contribution = times * matrix[i][j];
             
             totalSum += contribution;
             
         }
     }
     
     return totalSum;
     
 }
 
}
This post is licensed under CC BY 4.0 by the author.