动态规划解221. Maximal Square
来源:互联网 发布:晚睡对女生的危害知乎 编辑:程序博客网 时间:2024/06/14 09:06
题目
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 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.
题意分析
给定一个矩阵,求其中由’1’组成的正方形最大面积,从给出的矩阵来看,组成的最大正方形为m[1][2], m[1][3], m[2][2], m[2][3], 因此最大面积为4
思路分析
这是一道动态规划的题目,假设result[i][j]表示当前第i行第i列能得到最大正方形的边长。则当matrix[i][j]为’0’时,result[i][j]= 0,当matrix[i][j]为’1’时,则要考虑它是否能扩大之前的正方形,因此需要观察它的左边,它的上边,以及它的左上边,因此它的递推式为:
result[i][j] = min(result[i-1][j-1], min(result[i-1][j], result[i][j-1])) + 1
根据递推式遍历整个matrix,就得到result集合,使用一个res去记录最大正方形的边长,最后返回res*res则是答案
AC代码
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { int row = matrix.size(); if (row == 0) { return 0; } int col = matrix[0].size(); vector<vector<int>> result; for (int i = 0; i < row; ++i) { result.push_back(vector<int>()); for (int j = 0; j < col; ++j) { result[i].push_back(0); } } int res = 0; for (int i = 0; i < col; ++i) { result[0][i] = matrix[0][i] - 48; if (result[0][i] > res) { res = result[0][i]; } } for (int j = 0; j < row; ++j) { result[j][0] = matrix[j][0] - 48; if (result[j][0] > res) { res = result[j][0]; } } for (int i = 1; i < row; ++i) { for (int j = 1; j < col; ++j) { if (matrix[i][j] == '0') { result[i][j] = 0; } else { if (result[i][j - 1] > 0 && result[i - 1][j] > 0 && result[i - 1][j - 1] > 0) { result[i][j] = min(result[i - 1][j - 1], min(result[i][j - 1], result[i - 1][j])) + 1; } else { result[i][j] = 1; } if (result[i][j] > res) res = result[i][j]; } } } return res*res; }};
阅读全文
0 0
- 动态规划解221. Maximal Square
- LeetCode 221.Maximal Square 动态规划
- LeetCode 85. Maximal Rectangle&221. Maximal Square--动态规划
- 【动态规划】leetcode - Maximal Square
- 03动态规划-03maximal-square
- [leetcode] 221 Maximal Square(最大全1正方形 &动态规划)
- [leetcode] 221 Maximal Square(最大全1正方形 &动态规划)
- 221.Maximal Square
- [leetcode] 221.Maximal Square
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- leetcode 221. Maximal Square
- 221. Maximal Square LeetCode
- 221. Maximal Square
- 221. Maximal Square
- LeetCode 221. Maximal Square
- 221. Maximal Square
- LeetCode *** 221. Maximal Square
- Django网站建设-用户登陆机制,session/cookies
- 理解矩阵
- Python
- Redis入门(三)—— 使用redis客户端连接windows和linux下的redis并解决无法连接redis的问题
- 七周二次课(12月5日) 13.8 hash类型操作 13.9 其他常用操作
- 动态规划解221. Maximal Square
- python中filter()函数
- Python,ex16 文件操作
- PyCharm
- 设置Tomcat的UTF-8编码
- docker搭建私有仓库以及使用
- Linux网络编程-TCP
- 从Properties.Resources里的byte生成word文件
- 07 用URL正则实现文章链接跳转