Maximal Square -- leetcode
来源:互联网 发布:邮政储蓄银行软件 编辑:程序博客网 时间:2024/05/22 12:01
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 0Return 4.
基本思路:
动态规划。
逐行逐列扫描。计算以当前位置为右下角的最大矩形。设其边长为square(i,j)
当matrix[i][j] 为 '1'时
需要的参数为:
1. square(i-1,j-1),即与当前位置相邻的左上角
2. 当前位置连续为'1'的个数(列向,或纵向),设为height(j)
3. 当前位置连续为'1'的个数(行向,或水平向),设为width
直观理解为,在一个矩形的,右边,和下边,各贴上一块东西,构成新的矩形。
新矩形的边长,则为上面三者取最小值。
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { int ans = 0; if (matrix.empty() || matrix[0].empty()) return ans; const int M = matrix.size(); const int N = matrix[0].size(); vector<int> height(N); vector<int> square(height); for (int i=0; i<M; i++) { int width = 0; int last = 0; for (int j=0; j<N; j++) { const int bak = square[j]; if (matrix[i][j] == '1') { square[j] = min(last, min(width, height[j])) + 1; ans = max(ans, square[j]); ++width; ++height[j]; } else { square[j] = 0; width = 0; height[j] = 0; } last = bak; } } return ans * ans; }};
此处用到了两个一维数组。
此处可以进一步进行内存优化。 省掉一个数组。即height数组省去。
width也省去计算。
完全从前面已经计算的矩形中求得。
即从当前点的左方,正上,左上角的矩形边长,求出当前点的边长。
下面算法中变量prev,表示左方的矩形边长;
last表示左上角的矩形边长;
square[j]表示正上的矩形边长。
即所谓的滚动数组概念。使用一维数组代替二维数组的一种通用做法。
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { int ans = 0; if (matrix.empty() || matrix[0].empty()) return ans; const int M = matrix.size(); const int N = matrix[0].size(); vector<int> square(N); for (int i=0; i<M; i++) { int prev = 0; int last = 0; for (int j=0; j<N; j++) { const int bak = square[j]; if (matrix[i][j] == '1') { square[j] = min(last, min(prev, square[j])) + 1; ans = max(ans, square[j]); } else { square[j] = 0; } last = bak; prev = square[j]; } } return ans * ans; }};
0 0
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- [leetcode] Maximal Square
- Maximal Square Leetcode Java
- [leetcode] Maximal Square
- leetcode 221: Maximal Square
- LeetCode Maximal Square
- Maximal Square - LeetCode 221
- #leetcode#Maximal Square
- LeetCode Maximal Square
- [LeetCode] Maximal Square
- [LeetCode]Maximal Square
- leetcode Maximal Square
- leetcode Maximal Square
- Leetcode 221 Maximal Square
- leetCode(27):Maximal Square
- [leetCode] Maximal Square
- Leetcode 221 Maximal Square
- Spring4新特性——注解、脚本、任务、MVC等其他特性改进
- Understanding mappedBy annotation in Hibernate
- Light oj 1050 - Marbles(概率dp)
- 根据文字需求得到具体查询sql
- android 玩转ContentProvider之一--实现ContentProvider操作数据库
- Maximal Square -- leetcode
- Android Fragment、Activity、Dialog 各种组件直接数据共享,更新通知
- 使用Javah命令生成头文件
- 4.Selenium与TestNG测试框架结合
- JQuery上传插件Uploadify使用详解
- hdu 5410 CRB and His Birthday 背包问题 2015 Multi-University Training Contest 10 ★★★
- android textview 部分文字点击事件
- 采用共享jar包部署struts2+spring集成项目会遇到的问题
- win7-32位下php5.3.13配置连接sqlServer2008