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

Sign up
Appearance settings

Commit 1ee5961

Browse files
Add solution for Count Square Submatrices with All Ones
1 parent 8c71dbe commit 1ee5961

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,5 @@ Algorithm exercises from LeetCode implemented in Java (v11) and JavaScript.
127127
- Counting Bits | [Problem](https://leetcode.com/problems/counting-bits) | [Java Solution](src/javacode/solutions/CountingBits.java)
128128

129129
### Dynamic Programming
130-
- Count Sorted Vowel Strings | [Problem](https://leetcode.com/problems/count-sorted-vowel-strings) | [Java Solution](src/javacode/solutions/CountSortedVowelStrings.java)
130+
- Count Sorted Vowel Strings | [Problem](https://leetcode.com/problems/count-sorted-vowel-strings) | [Java Solution](src/javacode/solutions/CountSortedVowelStrings.java)
131+
- Count Square Submatrices with All Ones | [Problem](https://leetcode.com/problems/count-square-submatrices-with-all-ones) | [Java Solution](src/javacode/solutions/CountSquareSubmatrices.java)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package javacode.solutions;
2+
3+
import java.util.Arrays;
4+
5+
// [Problem] https://leetcode.com/problems/count-square-submatrices-with-all-ones
6+
class CountSquareSubmatrices {
7+
// Dynamic programming
8+
// O(m * n) time, O(1) space
9+
// where m = row size, n = column size
10+
public int countSquares(int[][] matrix) {
11+
int count = 0;
12+
int rowSize = matrix.length, colSize = matrix[0].length;
13+
for (int row = 0; row < rowSize; row++) {
14+
for (int col = 0; col < colSize; col++) {
15+
if (matrix[row][col] == 1 && row > 0 && col > 0) {
16+
matrix[row][col] = Math.min(matrix[row - 1][col - 1], Math.min(matrix[row - 1][col], matrix[row][col - 1])) + 1;
17+
}
18+
count += matrix[row][col];
19+
}
20+
}
21+
return count;
22+
}
23+
24+
// Test
25+
public static void main(String[] args) {
26+
CountSquareSubmatrices solution = new CountSquareSubmatrices();
27+
28+
int[][] input = {
29+
{0, 1, 1, 1},
30+
{1, 1, 1, 1},
31+
{0, 1, 1, 1}
32+
};
33+
int expectedOutput = 15;
34+
int actualOutput = solution.countSquares(input);
35+
36+
System.out.println("Test passed? " + (expectedOutput == actualOutput));
37+
}
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /