Skip to content

Commit 49d0896

Browse files
Create Day 21 Count Square Submatrices with All Ones.cpp
1 parent 04f6ff9 commit 49d0896

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
PROBLEM:
2+
3+
4+
5+
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
6+
7+
8+
Example 1:
9+
Input: matrix =
10+
[
11+
[0,1,1,1],
12+
[1,1,1,1],
13+
[0,1,1,1]
14+
]
15+
Output: 15
16+
Explanation:
17+
There are 10 squares of side 1.
18+
There are 4 squares of side 2.
19+
There is 1 square of side 3.
20+
Total number of squares = 10 + 4 + 1 = 15.
21+
22+
Example 2:
23+
Input: matrix =
24+
[
25+
[1,0,1],
26+
[1,1,0],
27+
[1,1,0]
28+
]
29+
Output: 7
30+
Explanation:
31+
There are 6 squares of side 1.
32+
There is 1 square of side 2.
33+
Total number of squares = 6 + 1 = 7.
34+
35+
36+
Constraints:
37+
38+
1. 1 <= arr.length <= 300
39+
2. 1 <= arr[0].length <= 300
40+
3. 0 <= arr[i][j] <= 1
41+
42+
43+
44+
45+
SOLUTION:
46+
47+
48+
49+
class Solution {
50+
public:
51+
int countSquares(vector<vector<int>>& matrix) {
52+
53+
int i,j,n,m,ans=0;
54+
n=matrix.size();
55+
m=matrix[0].size();
56+
57+
vector<vector<int>> dp(n,vector<int>(m,0));
58+
59+
for(i=0;i<n;i++)
60+
{
61+
for(j=0;j<m;j++)
62+
{
63+
if( (i==0 || j==0 ) && matrix[i][j]==1)
64+
dp[i][j]=1;
65+
else if(matrix[i][j]==1)
66+
dp[i][j] = 1 +min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});
67+
68+
ans+=dp[i][j];
69+
}
70+
}
71+
72+
return ans;
73+
74+
}
75+
};

0 commit comments

Comments
 (0)