Leetcode Maximal Square
来源:互联网 发布:免费股票量能分析软件 编辑:程序博客网 时间:2024/06/05 02:39
Leetcode Maximal Square 相关代码,本算法使用dp算法完成,主要思想为:一列列的计算,计算每个元素右上解的最大square,并记录以其为右下角的square的信息(左边’1’的长度、以及相应square大小)。计算时,使用其左边的元素的信息进行相关计算,具体如下:
如果从上到元素相邻接的 ‘1’大于左边元素为右下角的square的边长,则判断当前元素为右下角的square边长能否增长1,如果能,应该有当前square的上边,在左侧元素的上边之上,如下:
xxxxx
yyyyx
yyyyx
yyyyx
其中x代表为新增的元素,其应为1, y为左侧元素为右下角的square。
注:此处纵向x为计算ajacent,横向x为记录左侧’1’的长度。
算法复杂度为o(n^2)。
相关代码与测试如下:
#include <iostream>#include <vector>using namespace std;// conclusion: use the left rectangle and one colmun to calculate the current valueclass Solution {public: int maximalSquare(vector<vector<char> >& matrix) { if (matrix.size() == 0) { return 0; } if (matrix[0].size() == 0) { return 0; } int row_num = matrix.size(); int col_num = matrix[0].size(); vector<vector<int> > row(row_num, vector<int>(2, 0)); int max = 0; int ajacent = 0; for (int index = 0; index < col_num; index ++) { ajacent = 0; for (int j = 0; j < row_num; j ++) { if (matrix[j][index] == '1') { row[j][0] ++; ajacent ++; if (ajacent > row[j][1] && row[j - row[j][1]][0] >= row[j][1] + 1) { row[j][1] ++; max = row[j][1] > max? row[j][1] : max; } else { row[j][1] = ajacent > row[j][1]? row[j][1] : ajacent; } } else { row[j][0] = 0; ajacent = 0; row[j][1] = 0; } } } return max; }};int main(int argc, char * argv[]) { Solution so; vector<vector<char> > test(3, vector<char>(5, '1')); test[0][1] = '0'; test[1][3] = '0'; test[2][0] = '0'; int re = so.maximalSquare(test); cout<<"max:"<<re<<endl; return 0;}
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
- Linux 环境下 fork 函数和 exec 函数族的使用
- 用栈实现的整型数据的四则运算
- iOS UI基础-7.0 UIScrollView
- java二维数组定义
- Web API入门之移除XML格式(一)
- Leetcode Maximal Square
- css
- 开源一个基于天天团购的团购app
- Hibernate系列之核心开发接口
- LeetCode-Implement Queue using Stacks
- 欢迎使用CSDN-markdown编辑器
- Xcode6中segue取消原push与modal选项后新增选项的解释
- Binary Tree Paths
- First Bad Version