zoukankan      html  css  js  c++  java
  • leetcode221

    221. Maximal Square

    package leetcode;
    
    public class Solution221 extends Solution {
        @Override
        public void test() {
            char[][] matrix = {
                    {'1', '1', '1', '1', '1'},
                    {'1', '0', '1', '1', '1'},
                    {'0', '1', '1', '1', '0'},
                    {'1', '1', '1', '1', '1'},
                    {'1', '0', '1', '1', '1'},
            };
            System.out.println(maximalSquare(matrix));
        }
    
        public int maximalSquare(char[][] matrix) {
            // f(x, y)是(x, y)为正方形右下角的点时所能构成的最大正方形面积
            // 当f(x-1, y-1) != 0时,f(x, y)的取值可以分为两种情况:
            // (1) 当 f(x-1, y) != f(x, y-1)时, 取两者中的最小值;
            // (2) 当 f(x-1, y) == f(x, y-1)时,取两者中的最小值,假设f(x, y-1)较小,然后再取f(x-1, y-1)与f(x, y-1)中较小的值
            // 将得到的最小值开根号再加1,就是f(x, y)所能构成的最大正方形的边长
            if(matrix.length < 1 || matrix[0].length < 1) return 0;
            int[][] area = new int[matrix.length][matrix[0].length];
            int max = 0;
            for(int i=0; i<matrix.length; i++){
                for(int j=0; j<matrix[i].length; j++){
                    if (matrix[i][j]!='0'){
                        isSquare(matrix, area, i, j);
                    }
                    max = Math.max(max, area[i][j]);
                }
            }
            return max;
        }
    
        public void isSquare(char[][] matrix, int[][] area, int x, int y){
            if (x <= 0 || y <= 0 || area[x-1][y-1] == 0) {
                area[x][y] = matrix[x][y] - '0';
                return ;
            }
            int t = Math.min(area[x-1][y], area[x][y-1]);
            if (area[x - 1][y] == area[x][y - 1]) {
                t = Math.min(t, Math.abs(area[x - 1][y - 1]));
            }
            int sqrt = (int)Math.sqrt(t) + 1;
            area[x][y] = sqrt * sqrt;
        }
    }

  • 相关阅读:
    牛客-小V和gcd树
    CF-Codeforces Round #639 (Div. 2)-D-Monopole Magnets
    牛客-牛牛染颜色
    CF-637
    提高办公效率——快捷键
    FusionComputer虚拟机克隆后出现网卡服务重启失败解决办法
    centos7.5mini中Firewalld端口不通解决办法及想法
    FusionConputer热迁移过程记录
    Java集合框架之Iterable接口
    初识Java集合框架
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/12509788.html
Copyright © 2011-2022 走看看