Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Matrix Block Sum in C++
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 −
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
And k is 1, then the output will be −
| 12 | 21 | 16 |
| 27 | 45 | 33 |
| 24 | 39 | 28 |
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]
- if r and c are inside the matrix indices, then
- for c in range j – k to j + k
- for r in range i – k to i + k
- for j in range 0 to m – 1
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#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, ],]
Advertisements