Skip to content

Commit dfe1f62

Browse files
committed
add: LargestSquareInAMatrix
1 parent 933db30 commit dfe1f62

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class LargestSquareInAMatrix {
2+
public int largestSquareInAMatrix(int[][] matrix) {
3+
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
4+
return 0;
5+
}
6+
int m = matrix.length;
7+
int n = matrix[0].length;
8+
int[][] dp = new int[m][n];
9+
int maxLen = 0;
10+
// Base case: If a cell in row 0 is 1, the largest square ending there has a
11+
// length of 1.
12+
for (int j = 0; j < n; j++) {
13+
if (matrix[0][j] == 1) {
14+
dp[0][j] = 1;
15+
maxLen = 1;
16+
}
17+
}
18+
// Base case: If a cell in column 0 is 1, the largest square ending there has
19+
// a length of 1.
20+
for (int i = 0; i < m; i++) {
21+
if (matrix[i][0] == 1) {
22+
dp[i][0] = 1;
23+
maxLen = 1;
24+
}
25+
}
26+
// Populate the rest of the DP table.
27+
for (int i = 1; i < m; i++) {
28+
for (int j = 1; j < n; j++) {
29+
if (matrix[i][j] == 1) {
30+
// The length of the largest square ending here is determined by
31+
// the smallest square ending at the neighboring cells (left,
32+
// top-left, top), plus 1 to include this cell.
33+
dp[i][j] = 1 + Math.min(dp[i - 1][j], Math.min(dp[i - 1][j - 1], dp[i][j - 1]));
34+
}
35+
maxLen = Math.max(maxLen, dp[i][j]);
36+
}
37+
}
38+
return maxLen * maxLen;
39+
}
40+
}

0 commit comments

Comments
 (0)