forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
38 lines (36 loc) · 1.22 KB
/
Solution.cs
File metadata and controls
38 lines (36 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
namespace LeetCodeNet.G0201_0300.S0221_maximal_square {
// #Medium #Array #Dynamic_Programming #Matrix #Dynamic_Programming_I_Day_16
// #Top_Interview_150_Multidimensional_DP #Big_O_Time_O(m*n)_Space_O(m*n)
// #2025_06_15_Time_3_ms_(96.90%)_Space_67.76_MB_(80.23%)
public class Solution {
public int MaximalSquare(char[][] matrix) {
int m = matrix.Length;
if (m == 0) {
return 0;
}
int n = matrix[0].Length;
if (n == 0) {
return 0;
}
int[][] dp = new int[m + 1][];
for (int i = 0; i <= m; i++) {
dp[i] = new int[n + 1];
}
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
// 1 + minimum from cell above, cell to the left, cell diagonal upper-left
int next = 1 + Math.Min(dp[i][j], Math.Min(dp[i + 1][j], dp[i][j + 1]));
// keep track of the maximum value seen
if (next > max) {
max = next;
}
dp[i + 1][j + 1] = next;
}
}
}
return max * max;
}
}
}