Abhilash
Abhilash

Reputation: 33

Given a matrix of size nxm, how can we calculate the sum of all possible square matrices of size (L)?

Given this 3x3(nxm) matrix, how can I traverse and get the sum of all possible square-submatrices i.e(1x1,2x2 in this particular case)

2 2 3
3 4 5
4 5 5

I know here, every element is an individual submatrix(1x1), and the rest square-submatrices are as follow:

2 2
3 4
2 3
4 5
3 4
4 5
4 5
5 5

I've tried my approach and failed multiple times, the main reason is I get confused with matrices in programming. My Approach: Here, 'l' is size of square-sub matrix, 'n' size of rows of main matrix, 'm' size of cols of main matrix,

for (i=0; i<n-l; i++){
            for (j=1; j<n-i+1; j++){
                sum = 0;
                for (p=i; p<l+i; p++){
                    for (q=1; q<l+j+1; q++){
                        sum += a[p][q];
                    }
                }
               cout << sum << endl;
            }
            l++;
        }

Upvotes: 0

Views: 1297

Answers (2)

Arsandi Saputra
Arsandi Saputra

Reputation: 26

This is the solution of your case.

for(int i=0; i+(l-1)<n; i++){
    for(int j=0; j+(l-1)<m; j++){
        int sum = 0;
        for(int a=0; a<l; a++){
            for(int b=0; b<l; b++){
                sum += matrix[i+a][j+b];
            }
        }
        cout << sum << endl;
    }
}

or you can try to run the full code on Tio.run

Upvotes: 1

Arty
Arty

Reputation: 16747

I rewrote your code to make it correct, also made full example:

Try it online!

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<std::vector<int>> a = {{2, 2, 3}, {3, 4, 5}, {4, 5, 5}};
    size_t n = a.size(), m = a.size() > 0 ? a[0].size() : 0;
    
    for (size_t l = 1; l <= std::min(n, m); ++l)
        for (size_t i = 0; i < n - l + 1; ++i)
            for (size_t j = 0; j < m - l + 1; ++j) {
                int sum = 0;
                for (size_t p = i; p < i + l; ++p)
                    for (size_t q = j; q < j + l; ++q)
                        sum += a[p][q];
                std::cout << l << ", " << i << ", " << j << ": " << sum << std::endl;
            }
}

Input:

2 2 3
3 4 5
4 5 5

Output:

1, 0, 0: 2
1, 0, 1: 2
1, 0, 2: 3
1, 1, 0: 3
1, 1, 1: 4
1, 1, 2: 5
1, 2, 0: 4
1, 2, 1: 5
1, 2, 2: 5
2, 0, 0: 11
2, 0, 1: 14
2, 1, 0: 16
2, 1, 1: 19
3, 0, 0: 33

Upvotes: 1

Related Questions