Matrix Block Sum in C++

C++Server Side ProgrammingProgramming

Suppose we have one m * n matrix called mat and an integer K, we have to find another matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for i - K <= r <= i + K, j - K <= c <= j + K, and (r, c) is a valid position in the matrix. So if the input is like −

123
456
789

And k is 1, then the output will be −

122116
274533
243928

To solve this, we will follow these steps −

  • n := number of rows, and m = number of columns
  • define a matrix ans, whose order is n x m
  • for i in range 0 to n – 1
    • for j in range 0 to m – 1
      • for r in range i – k to i + k
        • for c in range j – k to j + k
          • if r and c are inside the matrix indices, then
            • ans[i, j] := ans[i, j] + mat[r, c]
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
      int n = mat.size();
      int m = mat[0].size();
      vector < vector <int> > ans(n , vector <int> (m));
      for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++){
            for(int r = i - k;r <= i + k; r++){
               for(int c = j - k; c <= j + k; c++){
                  if(r>= 0 && r < n && c >= 0 && c < m){
                     ans[i][j] += mat[r][c];
                  }
               }
            }
         }
      }
      return ans;
   }
};
main(){
   vector<vector<int>> v1 = {{1,2,3},{4,5,6},{7,8,9}};
   Solution ob;
   print_vector(ob.matrixBlockSum(v1, 1));
}

Input

[[1,2,3],[4,5,6],[7,8,9]]
1

Output

[[12, 21, 16, ],[27, 45, 33, ],[24, 39, 28, ],]
raja
Published on 18-Mar-2020 10:14:10
Advertisements