zoukankan      html  css  js  c++  java
  • LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium

    题目:

    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] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1; where matrix[i][j] == 1

    根据此方程,就可以写出如下的代码:

    代码展示:

     1 #include <iostream>
     2 #include <vector>
     3 #include <cstring>
     4 using namespace std;
     5 
     6 //dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
     7 //where matrix[i][j] == 1
     8 int maximalSquare(vector<vector<char>>& matrix) 
     9 {
    10     if (matrix.empty())
    11         return 0;
    12 
    13     int rows = matrix.size();//行数
    14     int cols = matrix[0].size(); //列数
    15 
    16     vector<vector<int> > dp(rows+1, vector<int>(cols+1, 0));
    17     /*
    18         0 0 0 0 0 0
    19         0 1 0 1 0 0
    20         0 1 0 1 1 1
    21         0 1 1 1 1 1
    22         0 1 0 0 1 0
    23     */
    24     int result = 0; //return result
    25 
    26     for (int i = 0; i < rows; i ++) {
    27         for (int j = 0; j < cols; j ++) {
    28             if (matrix[i][j] == '1') {
    29                 int temp = min(dp[i][j], dp[i][j+1]);
    30                 dp[i+1][j+1] = min(temp, dp[i+1][j]) + 1;
    31             }
    32             else 
    33                 dp[i+1][j+1] = 0;
    34             
    35             result = max(result, dp[i+1][j+1]);
    36         }
    37     }
    38     return result * result; //get the area of square;
    39 }
    40 
    41 // int main()
    42 // {
    43 //     char *ch1 = "00000";
    44 //     char *ch2 = "00000";
    45 //     char *ch3 = "00000";
    46 //     char *ch4 = "00000";
    47 //     vector<char> veccol1(ch1, ch1 + strlen(ch1));
    48 //     vector<char> veccol2(ch2, ch2 + strlen(ch2));
    49 //     vector<char> veccol3(ch3, ch3 + strlen(ch3));
    50 //     vector<char> veccol4(ch4, ch4 + strlen(ch4));
    51 //     
    52 //     vector<vector<char> > vecrow;
    53 //     vecrow.push_back(veccol1);
    54 //     vecrow.push_back(veccol2);
    55 //     vecrow.push_back(veccol3);
    56 //     vecrow.push_back(veccol4);
    57 //     
    58 //     vector<vector<char> > vec;
    59 //     cout << maximalSquare(vec);
    60 //     return 0;
    61 // }
  • 相关阅读:
    数据库基本操作
    守护线程
    线程使用的场景
    创建多线程
    用正则表达式去截取网页里文字的方法。参数为读取的网页源代码
    文章生成器,Split方法截取字符串。从硬盘读取文件,和向硬盘存储文件参考代码
    winform 阶段学习总结
    Windowform 窗体关联数据库存储,读取图片,参考代码
    windows form窗体应用程序,建一个记事本参考代码,重点是打开,保存,另存为
    js实现相册翻页,滚动,切换,轮播功能
  • 原文地址:https://www.cnblogs.com/bakari/p/5073519.html
Copyright © 2011-2022 走看看