给定一个方阵,其中每个单元(像素)非黑即白。设计一个算法,找出 4 条边皆为黑色像素的最大子方阵。
返回一个数组 [r, c, size] ,其中 r, c 分别代表子方阵左上角的行号和列号,size 是子方阵的边长。若有多个满足条件的子方阵,返回 r 最小的,若 r 相同,返回 c 最小的子方阵。若无满足条件的子方阵,返回空数组。
示例 1:
输入:
[
[1,0,1],
[0,0,1],
[0,0,1]
]
输出: [1,0,2]
解释: 输入中 0 代表黑色,1 代表白色,标粗的元素即为满足条件的最大子方阵
示例 2:
输入:
[
[0,1,1],
[1,0,1],
[1,1,0]
]
输出: [0,0,1]
提示:
matrix.length == matrix[0].length <= 200
方法1:动态规划+两辅助数组
public int[] findSquare(int[][] mat) {
int R = mat.length, C = mat[0].length;
int[][] maxRow = new int[R][C];
int[][] maxCol = new int[R][C];
for (int r = R - 1; r >= 0; --r) {
for (int c = C - 1; c >= 0; --c) {
if (mat[r][c] == 0) {
maxRow[r][c] = 1;
if (c < C - 1) maxRow[r][c] += maxRow[r][c + 1];
maxCol[r][c] = 1;
if (r < R - 1) maxCol[r][c] += maxCol[r + 1][c];
}
}
}
int[] res = new int[3];
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (mat[r][c] == 0) {
int upper = Math.min(maxRow[r][c], maxCol[r][c]);
int bound = res[2];
for (int size = upper; size > bound; size--) {
if (maxRow[r + size - 1][c] >= size && maxCol[r][c + size - 1] >= size) {
res[0] = r;
res[1] = c;
res[2] = size;
break;
}
}
}
}
}
if (res[2] == 0) return new int[]{};
return res;
}