边界为1的最大子方阵优化
4,4 3,1 2,1 1,1
1,3 0,0 0,0 0,0
4,2 3,2 2,1 1,2
2,1 1,1 0,0 1,1
2
Process finished with exit code 0
思路: 先初始化最后一行,从后面开始到前遍历,将子方阵解析成上述情况,最后在进行check。check其实就是判断4个点。这四个点为:
4(!),4(!) 3,1(!) 2,1 1,1
1(!),3 0,0 0,0 0,0
4,2 3,2 2,1 1,2
2,1 1,1 0,0 1,1
public class 边界为1的最大子方阵优化 {
public static void main(String[] args) {
int[][] A = {
{0, 1, 1, 1, 1},
{0, 1, 0, 1, 1},
{0, 1, 1, 1, 1},
{0, 1, 1, 1, 1},
{0, 1, 0, 1, 1}
};
A=new int[][]{
{1, 1, 1, 1},
{1, 0, 0, 0},
{1, 1, 1, 1},
{1, 1, 0, 1},
};
generateHelpRec(A);
print(rec, A.length);
int res = solve(A);
System.out.println(res);
}
private static void print(int[][][] rec, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(rec[i][j][0] + "," + rec[i][j][1] + "\t");
}
System.out.println();
}
}
private static void generateHelpRec(int[][] A) {
int N = A.length;
rec = new int[N][N][2];
int row = N - 1;
//初始化最后一行
for (int j = N - 1; j >= 0; j--) {
int value = A[row][j];
if (value == 1) {
if (j == N - 1) {
rec[row][j][0] = 1;//右侧连续1的个数
}
else {
rec[row][j][0] = rec[row][j + 1][0] + 1;
}
rec[row][j][1] =1;
}
}
row--;
for (int i = row; i >= 0; i--) {
for (int j = N - 1; j >= 0; j--) {
int value = A[i][j];
if (value == 1) {
if (j == N - 1)
rec[i][j][0] = 1;//右侧连续1的个数
else
rec[i][j][0] = rec[i][j + 1][0] + 1;
rec[i][j][1] = rec[i+1][j][1] + 1;//向下连续1的个数
}
}
}
}
static int[][][]rec;
private static int solve(int[][] A) {
int N = A.length;
int n = N;
while (n > 0){
for (int i = 0; i < N; i++){
if (i + n > N) break;
l3:
for (int j = 0; j < N; j++) {
if (j + n > N) break;
if (check(i, j, n))
return n;
}
}
n--;
}
return n;
}
private static boolean check(int i, int j, int n){
//左上角那个点往右数的1的数目要>=n
//左上角那个点往下数的1的数目要>=n
//右上角那个点往下数的1的数目要>=n
//左下角那个点往右数的1的数目要>=n
if (rec[i][j][0]>=n&&rec[i][j][1]>=n&&rec[i][j+n-1][1]>=n&&rec[i+n-1][j][0]>=n)
return true;
return false;
}
}