Skip to content

Commit 3d78157

Browse files
committed
updated CountSquareSubmatricesWithAllOnes with DP solution
1 parent effb6df commit 3d78157

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package Medium.CountSquareWithOnes;
2+
3+
public class Driver {
4+
5+
public static void main(String[] args) {
6+
Solution sol = new Solution();
7+
int[][] matrix = {{0,1,1,1}, {1,1,1,1}, {0,1,1,1}};
8+
System.out.println("output: " + sol.countSquares(matrix));
9+
}
10+
11+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package Medium.CountSquareWithOnes;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Solution
8+
*/
9+
public class Solution {
10+
11+
public int countSquares(int[][] matrix) {
12+
int count = 0;
13+
// covert primitive int array into ArrayList for easier manipulation
14+
List<List<Integer>> mat = new ArrayList<>();
15+
for (int[] row: matrix) {
16+
List<Integer> list = new ArrayList<>();
17+
for (int num: row) {
18+
list.add(num);
19+
}
20+
mat.add(list);
21+
}
22+
// System.out.println("=== DEBUG: PRINT ARRAYLIST ===");
23+
// System.out.println(mat.toString());
24+
// go through each col by row
25+
for (int i = 0; i < mat.size(); i++) {
26+
for (int j = 0; j < mat.get(0).size(); j++) {
27+
// System.out.printf("=== %d, %d: %d ===\n", i, j, mat.get(i).get(j));
28+
if (i > 0 && j > 0 && mat.get(i).get(j) > 0) {
29+
// accumulate
30+
int min = Math.min(Math.min(mat.get(i-1).get(j), mat.get(i).get(j-1)), mat.get(i-1).get(j-1));
31+
// System.out.println("MIN: " + min);
32+
mat.get(i).set(j, mat.get(i).get(j)+min);
33+
}
34+
count += mat.get(i).get(j);
35+
// System.out.println("Count: " + count);
36+
}
37+
}
38+
return count;
39+
}
40+
}

0 commit comments

Comments
 (0)