
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
Find Number of Non-Zero Submatrices in C++
Suppose we are given a matrix that contains only two values; 1s and 0s. We have to find out the number of submatrices in the given matrix that contains all 1s. We print the value as output.
So, if the input is like
0 | 0 | 1 | 0 |
0 | 1 | 0 | 0 |
0 | 1 | 0 | 1 |
1 | 1 | 0 | 1 |
then the output will be 12.
To solve this, we will follow these steps −
- n := size of matrix
- m := size of matrix[0]
- Define an array add of size: n+1 x m+1.
- for initialize i := 0, when i < n, update (increase i by 1), do −
- for initialize j := 0, when j < m, update (increase j by 1), do −
- add[i + 1, j + 1] + = matrix[i, j]
- add[i + 1, j + 1] + = add[i, j + 1]
- add[i + 1, j + 1] + = add[i + 1, j]
- add[i + 1, j + 1] - = add[i, j]
- for initialize j := 0, when j < m, update (increase j by 1), do −
- res := 0
- for initialize i := 0, when i < n, update (increase i by 1), do −
- for initialize j := 0, when j < m, update (increase j by 1), do −
- if not matrix[i, j] is non-zero, then −
- Ignore following part, skip to the next iteration
- for initialize k := 1, when k <= (n - i), update (increase k by 1), do −
- p := 0,
- q := m - j;
- while p <= q, do −
- x := (p + q) / 2
- a := k * x
- cur := add[i + k, j + x] - add[i, j + x] - add[i + k, j] + add[i, j]
- if cur is same as a, then −
- r := x
- p := x + 1
- otherwise,
- q := x - 1
- if r is same as 0, then −
- Come out from the loop
- res := res + r
- if not matrix[i, j] is non-zero, then −
- for initialize j := 0, when j < m, update (increase j by 1), do −
- return res
Example
Let us see the following implementation to get better understanding −
#include<bits/stdc++.h> using namespace std; int solve(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); int add[n + 1][m + 1]; memset(add, 0, sizeof(add)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { add[i + 1][j + 1] += matrix[i][j]; add[i + 1][j + 1] += add[i][j + 1]; add[i + 1][j + 1] += add[i + 1][j]; add[i + 1][j + 1] -= add[i][j]; } } int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!matrix[i][j]) continue; for (int k = 1; k <= (n - i); k++) { int p = 0, q = m - j; int r; while (p <= q) { int x = (p + q) / 2; int a = k * x; int cur = add[i + k][j + x] - add[i][j + x] - add[i + k][j] + add[i][j]; if (cur == a) { r = x; p = x + 1; } else q = x - 1; } if (r == 0) break; res += r; } } } return res; } int main() { vector<vector<int>> mat = {{0, 0, 1, 0}, {0, 1, 0, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}}; cout<< solve(mat) <<endl; return 0; }
Input
{{0, 0, 1, 0}, {0, 1, 0, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}}
Output
12
Advertisements