求最大正方形的边长

来源:互联网 发布:mysql增删改查实例 编辑:程序博客网 时间:2024/04/27 21:33

题干:先输入两个值,代表矩阵的宽和长,再依次输入矩阵中的值,只能是0或1,最后求矩阵中最大正方形的边长,该正方形里面要全是1。

如: 3 4

       0 0 0 0

       0 1 1 0

       0 1 1 0

输出:2


import java.util.*; public class Main {     public static void main(String[] args) {         Scanner sc = new Scanner(System.in);         int M = sc.nextInt();         int N = sc.nextInt();         int[][] arr = new int[M][N];         boolean flag = false;         for(int i=0; i<M; i++) {             for(int j=0; j<N; j++) {                 arr[i][j] = sc.nextInt();                 if(arr[i][j]==1){                     flag = true;                 }             }         }         if(!flag){             System.out.println(0);             return;         }         int[] left = new int[N];         int[] right = new int[N];         int[] height = new int[N];         Arrays.fill(right, N-1);         int maxLen = 1;         for(int i=0; i<M; i++) {             int l=0, r=N-1;             for(int j=0; j<N; j++) {                 if(arr[i][j] == 1) {                     left[j] = Math.max(left[j], l);                 } else {                     left[j] = 0;                     l = j + 1;                 }             }             for(int j=0; j<N; j++) {                 if(arr[i][j] == 1) {                     height[j]++;                 } else {                     height[j] = 0;                 }             }             for(int j=N-1; j>=0; j--) {                 if(arr[i][j] == 1) {                     right[j] = Math.min(right[j], r);                 } else {                     right[j] = N-1;                     r = j - 1;                 }             }             for(int j=0; j<N; j++) {                  maxLen = Math.max(maxLen,Math.min(right[j]-left[j]+1,height[j]));             }         }         System.out.println(maxLen);     } } 




0 0
原创粉丝点击