Skip to content

Commit 4c7b530

Browse files
solves maximal square in java
1 parent db3a9de commit 4c7b530

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/MaximalSquare.java

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// https://leetcode.com/problems/maximal-square
2+
// T: O(m * n)
3+
// S: O(m * n)
4+
5+
public class MaximalSquare {
6+
public int maximalSquare(char[][] matrix) {
7+
final int rows = matrix.length, columns = matrix[0].length;
8+
final int[][] dp = new int[rows][columns];
9+
10+
assignFirstRowInDPMatrix(dp, matrix);
11+
assignFirstColumnInDPMatrix(dp, matrix);
12+
13+
int maxSideLen = contains1(dp) ? 1 : 0;
14+
15+
for (int row = 1 ; row < rows ; row++) {
16+
for (int column = 1 ; column < columns ; column++) {
17+
if (isOne(matrix[row][column])) {
18+
dp[row][column] = min(dp[row - 1][column], dp[row][column - 1], dp[row - 1][column - 1]) + 1;
19+
} else dp[row][column] = 0;
20+
maxSideLen = Math.max(maxSideLen, dp[row][column]);
21+
}
22+
}
23+
24+
return maxSideLen * maxSideLen;
25+
}
26+
27+
private boolean contains1(int[][] dp) {
28+
return contains1InFirstRow(dp) || contains1InFirstColumn(dp);
29+
}
30+
31+
private boolean contains1InFirstRow(int[][] dp) {
32+
for (int element : dp[0]) {
33+
if (element == 1) return true;
34+
}
35+
return false;
36+
}
37+
38+
private boolean contains1InFirstColumn(int[][] dp) {
39+
for (int[] row : dp) {
40+
if (row[0] == 1) return true;
41+
}
42+
return false;
43+
}
44+
45+
private boolean isOne(char character) {
46+
return character == '1';
47+
}
48+
49+
private int min(int a, int b, int c) {
50+
return Math.min(a, Math.min(b, c));
51+
}
52+
53+
private void assignFirstRowInDPMatrix(int[][] dp, char[][] matrix) {
54+
for (int column = 0 ; column < matrix[0].length ; column++) {
55+
dp[0][column] = matrix[0][column] - '0';
56+
}
57+
}
58+
59+
private void assignFirstColumnInDPMatrix(int[][] dp, char[][] matrix) {
60+
for (int row = 0 ; row < matrix.length ; row++) {
61+
dp[row][0] = matrix[row][0] - '0';
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)