zoukankan      html  css  js  c++  java
  • 221. Maximal Square

    Problem statement:

    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.

    Solution:

    It looks like 85. Maximal Rectangle. But, there is big difference. This is DP problem, however, maximul rectangle needs tricky.

    The key point is what we want from DP? The answer is max side length of square.

    DP maintains a 2D array, dp[i][j] means the max side of length of square by current position.

    Initialization:

    dp[0][j] = matrix[0][j] - '0';
    
    dp[i][0] = matrix[i][0] - '0';

    DP formula. and update the max side length for each value.

    if(matrix[i][j] == '1'){
        dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
    }

    Return max_size * max_size;

    The time complexity is O(n * n)

    class Solution {
    public:
        int maximalSquare(vector<vector<char>>& matrix) {
            if(matrix.empty()){
                return 0;
            }
            int row = matrix.size();
            int col = matrix[0].size();
            vector<vector<int>> square_size(row, vector<int>(col, 0));
            int max_size = 0;
            for(int i = 0; i < row; i++){
                square_size[i][0] = matrix[i][0] - '0';
                max_size = max(max_size, square_size[i][0]);
            }
            for(int j = 0; j < col; j++){
                square_size[0][j] = matrix[0][j] - '0';
                max_size = max(max_size, square_size[0][j]);
            }
            for(int i = 1; i < row; i++){
                for(int j = 1; j < col; j++){
                    if(matrix[i][j] == '1'){
                        square_size[i][j] = min(square_size[i - 1][j - 1], min(square_size[i - 1][j], square_size[i][j - 1])) + 1;
                    }
                    max_size = max(max_size, square_size[i][j]);
                }
            }
            return max_size * max_size;
        }
    };
  • 相关阅读:
    【转】i18n实现前端国际化(实例)
    【转】SQL Pretty Printer for SSMS 很不错的SQL格式化插件
    windows server IIS启用Windows authentication
    【转】命令行下载各种网上各种视频
    解决python “No module named pip”
    【转】excel音标乱码
    【转】自动化部署之jenkins及简介
    【转】右键菜单管理
    【转】C# @作用
    【转】NGen
  • 原文地址:https://www.cnblogs.com/wdw828/p/6851507.html
Copyright © 2011-2022 走看看