题目:给定一个N*N的矩阵matrix,在这个矩阵中,只有0和1两种值,返回边框全是1的最大正方形的边长长度。
例如:
{0,1,1,1,1},
{0,1,0,0,1},
{0,1,0,0,1},
{0,1,1,1,1},
{0,1,0,1,1}
其中,边框全是1的最大正方形的大小是4*4,返回4。
import java.sql.Array;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] arr = new int[][]{
{0,1,1,1,1},
{0,1,0,0,1},
{0,1,0,0,1},
{0,1,1,1,1},
{0,1,0,1,1}
};
int res = maxMatrix(arr);
System.out.println(res);
}
public static int maxMatrix(int[][] arr){
int n = arr.length;
while(n>0){
for(int i =0;i<arr.length;i++){
l3:
for(int j =0;j<arr.length;j++){
int newI = i+n-1,newJ = j+n-1;
if(newI>=arr.length|| newJ>=arr.length){
break;
}
//System.out.println(n+"----"+ i+","+j +"---"+newI+","+newJ);
if(arr[i][j] == 1 && arr[newI][newJ] == 1){
int row = i,col = j;
while(col<=newJ){
if(arr[row][col++] == 0)continue l3;
}
col--;
row++;
while(row<=newI){
if(arr[row++][col] == 0)continue l3;
}
row--;
col--;
while(col>=j){
if(arr[row][col--] == 0)continue l3;
}
col++;
row--;
while(row>=i){
if(arr[row--][col] == 0)continue l3;
}
return n;
}
}
}
n--;
}
return n;
}
}
方法二:预处理
import java.sql.Array;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
static int[][][] deal;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] arr = new int[][]{
{0,1,1,1,1},
{0,1,0,0,1},
{0,1,0,0,1},
{0,1,1,1,1},
{0,1,0,1,1}
};
int n = arr.length;
deal = new int[n][n][2];
make(arr,n);
int res = maxMatrix(arr);
System.out.println(res);
}
public static void make(int[][] matrix,int n){
for(int i = n-1;i>=0;i--){
for(int j = n-1;j>=0;j--){
if(matrix[i][j] == 1){
if(i == n-1){
deal[i][j][1] = 1;
}
if(j == n-1){
deal[i][j][0] = 1;
}
if(i+1<n){
deal[i][j][1] = deal[i+1][j][1]+1;
}
if(j+1<n){
deal[i][j][0] = deal[i][j+1][0]+1;
}
}
}
}
// for(int i =0;i<n;i++){
// for(int j =0;j<n;j++){
// System.out.print(deal[i][j][0]+","+deal[i][j][1]+" ");
// }
// System.out.println();
// }
}
public static int maxMatrix(int[][] arr){
int n = arr.length;
while(n>0){
for(int i =0;i<arr.length;i++){
if(i+n-1>=arr.length)break;
l3:
for(int j =0;j<arr.length;j++){
int newI = i+n-1,newJ = j+n-1;
if(newJ>=arr.length){
break;
}
//System.out.println(n+"----"+ i+","+j +"---"+newI+","+newJ);
// if(arr[i][j] == 1 && arr[newI][newJ] == 1){
// int row = i,col = j;
// while(col<=newJ){
// if(arr[row][col++] == 0)continue l3;
// }
// col--;
// row++;
// while(row<=newI){
// if(arr[row++][col] == 0)continue l3;
// }
// row--;
// col--;
// while(col>=j){
// if(arr[row][col--] == 0)continue l3;
// }
// col++;
// row--;
// while(row>=i){
// if(arr[row--][col] == 0)continue l3;
// }
// return n;
// }
if(deal[i][j][1]>=n && deal[i][j][0]>=n && deal[i][newJ][1]>=n && deal[newI][j][0]>=n){
return n;
}
}
}
n--;
}
return n;
}
}