Skip to content

Commit b184b48

Browse files
authored
Day 21 Solution
1 parent 4e294a0 commit b184b48

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// https://leetcode.com/problems/count-square-submatrices-with-all-ones/
2+
3+
class Solution {
4+
public int countSquares(int[][] matrix) {
5+
int mat[][] = new int[matrix.length + 1][matrix[0].length + 1];
6+
int sum = 0;
7+
8+
/* We can do Dynamic Programming by saving how many
9+
Squares can be formed using the bottom right corner
10+
element.
11+
*/
12+
13+
for(int i = 1; i <= matrix.length; i++)
14+
for(int j = 1; j <= matrix[0].length; j++)
15+
if(matrix[i - 1][j - 1] != 0)
16+
sum += (mat[i][j] = Math.min(Math.min(mat[i - 1][j], mat[i][j - 1]), mat[i - 1][j - 1]) + 1);
17+
18+
19+
/*
20+
Workin on the first example:
21+
===========================
22+
Matrix =
23+
[0,1,1,1],
24+
[1,1,1,1],
25+
[0,1,1,1]
26+
===========================
27+
mat after algorithm =
28+
[0,0,0,0,0],
29+
[0,0,1,1,1],
30+
[0,1,1,2,2],
31+
[0,0,1,2,3]
32+
===========================
33+
After summing all indicies, now we get the correct answer!
34+
*/
35+
36+
return sum;
37+
}
38+
}

0 commit comments

Comments
 (0)