算法分析与设计课程(14):【leetcode】 Maximal Square
来源:互联网 发布:淘宝流量下滑 编辑:程序博客网 时间:2024/04/29 15:33
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.
For example, given the following matrix:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.算法分析:
我们考虑brute force的方法,这种方法的机理就是就是把数组中每一个点都当成正方形的左顶点来向右下方扫描,来寻找最大正方形。具体的扫描方法是,确定了左顶点后,再往下扫的时候,正方形的竖边长度就确定了,只需要找到横边即可,这时候我们使用直方图的原理,从其累加值能反映出上面的值是否全为1。通过这种方法我们就可以找出最大的正方形。
代码如下:
#include<vector>class Solution{public:int maximalSquare(vector<vector<char>& matrix>){int res = 0;for(int i=0; i<matrix.size();++i){vector<int> v(matrix.size(),0);for(int j=i;j<matrix.size();++j){for(int k=0;k<matrix[j].sieze();++k){if(matrix[j][k]=='1')++v[k];}res = max(res,getSquareArea(v,j-i+1));}}return res;}int getSquareArea(vector<int>&v,int k){if(v.size()<k)return 0;for count = 0;for(in i=0;i<v.size();++i){if(v[i]!=k) count = 0;else ++count;if(count ==k)return k*k;}}
阅读全文
0 0
- 算法分析与设计课程(14):【leetcode】 Maximal Square
- 算法分析与设计课程(3):【leetcode】Permutations
- 算法分析与设计课程(4):【leetcode】Wildcard Matching
- 算法分析与设计课程(8):【leetcode】Sudoku Solver
- 算法分析与设计课程(9):【leetcode】Jump Game
- 算法分析与设计课程(10):【leetcode】Simplify Path
- 算法分析与设计课程(11):【leetcode】Gray Code
- 算法分析与设计课程(17):【leetcode】4Sum
- 算法分析与设计课程(18):【leetcode】Clone Graph
- LeetCode Exercise 14: Maximal Square
- 每周LeetCode算法题(八): 题目: 221. Maximal Square & 85. Maximal Rectangle
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- LeetCode 题解(117): Maximal Square
- Leetcode学习之Maximal Square(221)
- [LeetCode] Maximal Square(!!!!DP优化)
- LeetCode 221. Maximal Square(最大正方形)
- Leetcode 221 - Maximal Square(dp)
- [技巧分享-window10]win10新建或删除文件后不自动刷新
- 【备忘】Python编程实践视频教程+教材 27集 下载
- 说说 JavaScript 在 DOM2 级标准中定义的遍历规则
- UNICODE和UTF-8和ASCII互转
- Java笔记-基础
- 算法分析与设计课程(14):【leetcode】 Maximal Square
- 解决Failed to execute goal org.apache.maven.plugins
- 质数因子
- java多线程学习之ReentrantLock
- OpenGL蓝宝书源码学习(四)第三章——Scissor.cpp
- Linux平台卸载MySQL总结
- jquery.autocomplete 中文匹配时乱码
- oracle学习笔记02
- Android 动态权限管理学习指南