【Leetcode】221. Maximal Square
来源:互联网 发布:黑龙江网络作家协会 编辑:程序博客网 时间:2024/06/06 22:20
Description:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:
Given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.
思路:
本题可用动态规划来解。首先,先分析题目需求,本题需要在矩阵中找到由’1’构成的正方形,那么这个问题可看成找出含有’1’的连续横、纵、斜三个方向的数目,这样对问题就可以进行循环分解了。对每个位置为’1’的横、纵、斜三个方向进行判断,如果为’1’,则继续进行下一个元素的递归遍历,即可找到最大的矩形。为了提高运行效率,减少重复的操作,由于从左往右,从上至下进行遍历,那么可以对当前元素的值根据其左上侧的横、纵、斜方向的值来重新赋予,也就是累加操作。累加的值为横纵斜中的最小值,也就是遇到’0’之前的值,每次遇’0’则重新开始计算。最后利用一个参数来记录最大的那个值即可。
下面是使用C++的实现过程:
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); //边界状态 if(m==0){ return 0; } int n = matrix[0].size(); //边界状态2 if(n==1){ return matrix[0][0] == '1'; } int edge = 0; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { int d = i&&j ? matrix[i-1][j-1] : 0; int h = i ? matrix[i-1][j] : 0; int v = j ? matrix[i][j-1] : 0; int temp = d>h ? h : d; temp = temp>v ? v : temp; matrix[i][j] = (matrix[i][j]=='1') ? temp+1 : 0; edge = edge>matrix[i][j] ? edge : matrix[i][j]; } } return edge*edge; }};
0 0
- [leetcode] 221.Maximal Square
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- leetcode 221. Maximal Square
- 221. Maximal Square LeetCode
- LeetCode 221. Maximal Square
- LeetCode *** 221. Maximal Square
- LeetCode-221.Maximal Square
- leetcode.221. Maximal Square
- Leetcode 221. Maximal Square
- [leetcode]221. Maximal Square
- [LeetCode]--221. Maximal Square
- leetcode 221. Maximal Square
- Leetcode 221. Maximal Square
- Leetcode 221. Maximal Square
- [LeetCode]221. Maximal Square
- 【Leetcode】221. Maximal Square
- [leetcode]221. Maximal Square
- 如何获得持久的快乐?
- 深入理解Activity生命周期(二)
- eclipse出现"Building workspace". Java heap space
- 第四节:Maven坐标和依赖(下)
- Hadoop启动操作过程及常见错误
- 【Leetcode】221. Maximal Square
- jsp中select,radio,checkbox传参到后台
- 开启nginx和php-fpm的status状态监控
- gulp less编译css压缩和js压缩别名输出
- Spring学习笔记(一)
- sunday算法
- MySQL启程学习回忆录1
- UIFramework之对象池的使用
- 新手求助,C#窗口使用timer配合progressBar做循环进度条,为什么进度条不动