Skip to content

Commit 7591cf7

Browse files
committed
Maximal Square
1 parent cc76ce7 commit 7591cf7

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package leetcode.medium;
2+
3+
public class MaximalSquare {
4+
5+
int maximalSquare(char[][] matrix) {
6+
7+
int rows = matrix.length;
8+
int cols = matrix[0].length;
9+
int[][] dp = new int[rows][cols];
10+
int maxSide = 0;
11+
12+
// Fill the dp table
13+
for (int i = 0; i < rows; i++) {
14+
for (int j = 0; j < cols; j++) {
15+
if (matrix[i][j] == '1') {
16+
17+
// Special handling for the first row and first column
18+
if (i == 0 || j == 0)
19+
dp[i][j] = 1;
20+
else
21+
// For others, dp[i][j] is the minimum of the three neighbors
22+
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
23+
24+
maxSide = Math.max(maxSide, dp[i][j]);
25+
}
26+
}
27+
}
28+
29+
// Return the area of the largest square
30+
return maxSide * maxSide;
31+
}
32+
33+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package leetcode.medium;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class MaximalSquareTest {
8+
9+
private final MaximalSquare maximalSquare;
10+
11+
MaximalSquareTest() {
12+
maximalSquare = new MaximalSquare();
13+
}
14+
15+
@Test
16+
void testMaximalSquare1() {
17+
char[][] matrix = {
18+
{'1', '0', '1', '0', '0'},
19+
{'1', '0', '1', '1', '1'},
20+
{'1', '1', '1', '1', '1'},
21+
{'1', '0', '0', '1', '0'}
22+
};
23+
assertEquals(4, maximalSquare.maximalSquare(matrix));
24+
}
25+
26+
@Test
27+
void testMaximalSquare2() {
28+
char[][] matrix = {
29+
{'0', '1'},
30+
{'1', '0'}
31+
};
32+
assertEquals(1, maximalSquare.maximalSquare(matrix));
33+
}
34+
35+
@Test
36+
void testMaximalSquare3() {
37+
char[][] matrix = {
38+
{'0', '0'},
39+
{'0', '0'}
40+
};
41+
assertEquals(0, maximalSquare.maximalSquare(matrix));
42+
}
43+
44+
@Test
45+
void testMaximalSquare4() {
46+
char[][] matrix = {
47+
{'1', '1', '1', '1'},
48+
{'1', '1', '1', '1'},
49+
{'1', '1', '1', '1'},
50+
{'0', '0', '0', '0'}
51+
};
52+
assertEquals(9, maximalSquare.maximalSquare(matrix));
53+
}
54+
55+
@Test
56+
void testMaximalSquare5() {
57+
char[][] matrix = {
58+
{'1', '1', '1', '1'},
59+
};
60+
assertEquals(1, maximalSquare.maximalSquare(matrix));
61+
}
62+
}

0 commit comments

Comments
 (0)