【動態規劃】leetcode,規劃leetcode

來源:互聯網
上載者:User

【動態規劃】leetcode,規劃leetcode

題目:

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 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.


分析:

利用動態規劃求解。建立一個類node,node中成員變數left記錄每一個點的左邊有幾個1(包括該點本身)、up記錄上邊有幾個1(包括該點本身)、maxsize記錄該點對應的最大正方形的邊長(該點在正方形右下角)。若一個點是‘0’,則其對應的node是(0,0,0).

1、用變數res記錄最大正方形的邊長。

2、先依次處理輸入矩陣matrix左上方那個點、第一行和第一列,求出這些位置的node值。

3、再依次遍曆matrix剩下的點,對每一個點求出node值,並更新res。

4、返回res*res.


class node{  public:  int left,up,maxsize;  node():left(0),up(0),maxsize(0){}  node(int a,int b,int c):left(a),up(b),maxsize(c){}};class Solution {public:    int maximalSquare(vector<vector<char>>& matrix) {        if(matrix.empty() || matrix[0].empty())            return 0;                    int rows=matrix.size(),cols=matrix[0].size();        int res=0;        vector<vector<node>> dp(rows,vector<node>(cols));                if(matrix[0][0]=='1')        {            res=1;            dp[0][0]=node(1,1,1);        }        for(int j=1;j<cols;++j)        {            if(matrix[0][j]=='1')            {                res=1;                dp[0][j]=node(dp[0][j-1].left+1,1,1);            }        }        for(int i=1;i<rows;++i)        {            if(matrix[i][0]=='1')            {                res=1;                dp[i][0]=node(1,dp[i-1][0].up+1,1);            }        }                       for(int i=1;i<rows;++i)       {            for(int j=1;j<cols;++j)            {                  if(matrix[i][j]=='1')                  {                     dp[i][j].left=dp[i][j-1].left+1;                     dp[i][j].up=dp[i-1][j].up+1;                     if(matrix[i-1][j-1]!='1')                        dp[i][j].maxsize=1;                     else                     {                         int tmp=min(dp[i-1][j-1].maxsize+1,dp[i][j].left);                         tmp=min(tmp,dp[i][j].up);                          dp[i][j].maxsize=tmp;                     }                     res=max(res,dp[i][j].maxsize);                  }            }       }              return res*res;    }};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.