Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit b11f9f8

Browse filesBrowse files
committed
Add Java solution2 dynamic programming for day21: Count Square Submatrices with All Ones
1 parent c913961 commit b11f9f8
Copy full SHA for b11f9f8

File tree

Expand file treeCollapse file tree

1 file changed

+37
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+37
-0
lines changed

‎May-LeetCoding-Challenge/21-Count-Square-Submatrices-With-All-Ones/Count-Square-Submatrices-With-All-Ones.java

Copy file name to clipboardExpand all lines: May-LeetCoding-Challenge/21-Count-Square-Submatrices-With-All-Ones/Count-Square-Submatrices-With-All-Ones.java
+37Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,41 @@ private boolean isSquare(int[][] square, int xfrom, int xto, int yfrom, int yto)
2424
}
2525
return true;
2626
}
27+
}
28+
29+
/**
30+
* Dynamique programmingsolution
31+
* Runtime: 5 ms
32+
* Memory Usage: 49 MB
33+
* Time complexity: O(m*n)
34+
* Space complexity: O(1)
35+
*/
36+
class Solution2 {
37+
public int countSquares(int[][] matrix) {
38+
int length = matrix.length;
39+
if (length == 0) return 0;
40+
41+
int width = matrix[0].length;
42+
int res = 0;
43+
44+
for (int i = 0; i < length; i++) {
45+
for (int j = 0; j < width; j++) {
46+
if (matrix[i][j] == 0) continue;
47+
48+
// border
49+
if (i == 0 || j == 0) {
50+
res++;
51+
continue;
52+
}
53+
54+
// calculate min of different corner, and then plus himself
55+
int min = Math.min(matrix[i-1][j-1], Math.min(matrix[i-1][j], matrix[i][j-1]));
56+
matrix[i][j] += min;
57+
58+
res += matrix[i][j];
59+
}
60+
}
61+
62+
return res;
63+
}
2764
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.