Skip to content

Commit 44dffe0

Browse files
committed
add: LargestSquareInAMatrixOptimized
1 parent dfe1f62 commit 44dffe0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class LargestSquareInAMatrixOptimized {
2+
public int largestSquareInAMatrixOptimized(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[] prevRow = new int[n];
9+
int maxLen = 0;
10+
// Iterate through the matrix.
11+
for (int i = 0; i < m; i++) {
12+
int[] currRow = new int[n];
13+
for (int j = 0; j < n; j++) {
14+
// Base cases: if we’re in row 0 or column 0, the largest square ending
15+
// here has a length of 1. This can be set by using the value in the
16+
// input matrix.
17+
if (i == 0 || j == 0) {
18+
currRow[j] = matrix[i][j];
19+
} else {
20+
if (matrix[i][j] == 1) {
21+
// currRow[j] = 1 + min(left, top-left, top)
22+
currRow[j] = 1 + Math.min(currRow[j - 1], Math.min(prevRow[j - 1], prevRow[j]));
23+
}
24+
}
25+
maxLen = Math.max(maxLen, currRow[j]);
26+
}
27+
// Update 'prevRow' with 'currRow' values for the next iteration.
28+
prevRow = currRow;
29+
}
30+
return maxLen * maxLen;
31+
}
32+
}

0 commit comments

Comments
 (0)