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;
        }
    }

  • 相关阅读:
    数据结构与算法
    android vitamio的坑
    Fragment的坑
    scrollview里面嵌套listview的坑
    关于微信小程序的tabbar
    Intent初级学习
    HDU 4562 守护雅典娜
    SGU 542 Gena vs Petya
    [二] EditText and Button
    A Data Structure for Dynamic Trees
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/12509788.html
Copyright © 2011-2022 走看看