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
39
40
41
42
43
44
45
46
47
|
public static int largest1BorderedSquare(int[][] g) {
int n = g.length;
int m = g[0].length;
build(n, m, g);
// 特判:矩阵全是0
if (sum(g, 0, 0, n - 1, m - 1) == 0) {
return 0;
}
int ans = 1;
for (int a = 0; a < n; a++) {
for (int b = 0; b < m; b++) {
// 枚举左上角(a,b),从当前最大边长+1开始尝试
for (int c = a + ans, d = b + ans, k = ans + 1;
c < n && d < m; c++, d++, k++) {
// 边框1的个数 = 整个正方形的1 - 内部正方形的1
if (sum(g, a, b, c, d) - sum(g, a + 1, b + 1, c - 1, d - 1)
== (k - 1) << 2) {
ans = k;
}
}
}
}
return ans * ans;
}
// 构建二维前缀和数组
public static void build(int n, int m, int[][] g) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
g[i][j] += get(g, i, j - 1) + get(g, i - 1, j)
- get(g, i - 1, j - 1);
}
}
}
// 查询矩形区域和
public static int sum(int[][] g, int a, int b, int c, int d) {
return a > c ? 0 : (g[c][d] - get(g, c, b - 1)
- get(g, a - 1, d) + get(g, a - 1, b - 1));
}
// 安全获取值
public static int get(int[][] g, int i, int j) {
return (i < 0 || j < 0) ? 0 : g[i][j];
}
|