zoukankan      html  css  js  c++  java
  • leetcode 221. Maximal Square 求一个数组中由1组成的最大的正方形面积 ---------- java

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

    For example, given the following matrix:

    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0
    

    Return 4.

    给定一个二维数组,然后求里面由1组成的正方形的最大面积。

    1、以每一个1作为左上角的顶点,然后想右边和下面扩展,看正方形有多大。

    public class Solution {
        public int maximalSquare(char[][] matrix) {
            if (matrix.length == 0){
                return 0;
            }
            int row = matrix.length;
            int col = matrix[0].length;
            int result = 0;
            for (int i = 0; i < row; i++){
                for (int j = 0; j < col; j++){
                    if (matrix[i][j] == '1'){
                        result = Math.max(result, getNum(matrix, i, j));
                    }
                }
            }
            return result;
        }
        public int getNum(char[][] matrix, int row, int col){
            char ch = '1';
            int squre = 1;
            while (true){
                int num1 = row + squre;
                int num2 = col + squre;
                if (num1 >= matrix.length || num2 >= matrix[0].length){
                    return squre * squre;
                }
                for (int i = row; i <= num1 ; i++){
                    if (matrix[i][num2] != ch){
                        return squre * squre;
                    }
                }
                for (int i = col; i <= num2; i++){
                    if (matrix[num1][i] != ch){
                        return squre * squre;
                    }
                }
                squre++;
            }
        }
        
     
        
    }

    2、dp:遇到一个1,然后看[i - 1][j], [i - 1][j - 1],[i][j - 1]的值是多少,取最小值,然后加1。记录期间出现的最大值。

     但是实际上没有第一种的速度快,因为有一个额外的row*col空间。

    public class Solution {
        public int maximalSquare(char[][] matrix) {
            if (matrix.length == 0){
                return 0;
            }
            int result = 0;
            int[][] dp = new int[matrix.length + 1][matrix[0].length + 1];
            for (int i = 0; i < matrix.length; i++){
                for (int j = 0; j < matrix[0].length; j++){
                    if (matrix[i][j] == '1'){
                        dp[i + 1][j + 1] = Math.min(Math.min(dp[i + 1][j], dp[i][j]), dp[i][j + 1]) + 1;
                        result = Math.max(result, dp[i + 1][j + 1]);
                    }
                }
            }
            return result * result;
        }
    }

     

  • 相关阅读:
    mysql5.6 TIME,DATETIME,TIMESTAMP
    CMake 简单介绍 图
    mysql 源码编绎修改 FLAGS,调试MYSQL
    CHAR 详解
    关于MySQL的各种总结
    Shell编程速查手册
    cmake 手册系列
    编译安装GCC 5.2.0
    宽字符相关的输入输出
    Makefile
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6755972.html
Copyright © 2011-2022 走看看