• [LeetCode] Maximal Square


    Maximal Square

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    解题思路:

    最值问题考虑动态规划算法。设d[i][j]表示以matrix[i][j]为右下角的最慷慨阵大小,则有:

    d[i][j] = 0; matrix[i][j]='0'时

    d[i][j] = 1; matrix[i][j]='1'且(i==0||j==0)时

    d[i][j] = pow(min(min(sqrt(d[i-1][j-1]), sqrt(d[i-1][j])), sqrt(d[i][j-1])) + 1, 2); 其它情况。

    然后用一个变量maxSquare记录全局最大的方阵就可以。

    class Solution {
    public:
        int maximalSquare(vector<vector<char>>& matrix) {
            int n = matrix.size();
            if(n==0){
                return 0;
            }
            int m = matrix[0].size();
            vector<vector<int>> d(n, vector<int>(m, 0));    //以matrix[i][j]为右下角的最慷慨阵大小
            int maxSquare=0;
            
            for(int i = 0; i < n; i++){
                for(int j = 0; j < m; j++){
                    if(matrix[i][j]=='0'){
                        d[i][j] = 0;
                    }else{
                        if(i>0&&j>0){
                            d[i][j] = (int)pow(min((int)min((int)sqrt(d[i-1][j-1]), (int)sqrt(d[i-1][j])), (int)sqrt(d[i][j-1])) + 1, 2);
                        }else{
                            d[i][j] = 1;
                        }
                        maxSquare = max(maxSquare, d[i][j]);
                    }
                }
            }
            
            return maxSquare;
        }
    };

  • 相关阅读:
    IOS 网络请求中设置cookie
    七牛云存储 报错的问题
    理解RESTful架构
    关于APP接口设计
    WKWebView与Js实战(OC版)
    WKWebView API精讲(OC)
    iOS完整App资源收集
    WKWebView新特性及JS交互
    苹果app审核的规则总结
    Struts2实现文件的上传与动态下载功能。
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6791566.html
Copyright © 2020-2023  润新知