File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
May LeetCoding Challenge/Day_ 21 Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments