zoukankan      html  css  js  c++  java
  • LeetCode:Maximus Square(DP)

    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.

       dp[i][j]表示以坐标(i,j)为右下角的形成的正方形的最大边长。

     dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1;
     1 class Solution {
     2 public:
     3     int maximalSquare(vector<vector<char>>& matrix) {
     4         
     5         if(matrix.empty()) return 0;
     6         int M=matrix.size();
     7         int N=matrix[0].size();
     8         int result=0;
     9         
    10         vector<vector<int>> dp(M,vector<int>(N,0));
    11         
    12         for(int j=0;j<N;++j)
    13             if(matrix[0][j]=='1')
    14             {
    15                 dp[0][j]=1;
    16                 result=1;
    17             }
    18          for(int i=0;i<M;++i)
    19             if(matrix[i][0]=='1')
    20             {
    21                 dp[i][0]=1;
    22                 result=1;
    23             }
    24         
    25         for(int i=1;i<M;++i)
    26             for(int j=1;j<N;++j)
    27                 if(matrix[i][j]=='1')
    28                 {
    29                     dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1;
    30                     res=max(result,dp[i][j]);
    31                 }
    32         
    33         return result*result;
    34                     
    35         
    36     }
    37 };
  • 相关阅读:
    再逛开心网
    WAPM
    win2003安装flash cs4
    [AS3][物体的运动]
    转sql产生百万记录
    KeyedList
    timer 焦点
    sql优化
    灰色
    参数
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4721450.html
Copyright © 2011-2022 走看看