前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium

LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium

作者头像
Linux云计算网络
发布2018-01-11 10:59:21
1.2K0
发布2018-01-11 10:59:21
举报

题目:

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 // }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-12-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档