Maximal Square
2015-09-29 02:30
330 查看
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:
Return 4.
Runtime: 12ms.
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.
Runtime: 12ms.
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.empty() || matrix[0].empty()) return 0; int row = matrix.size(); int col = matrix[0].size(); vector<vector<int> > dp(row, vector<int>(col, 0)); int result = 0; for(int i = 0; i < row; i++) if(matrix[i][0] == '1'){ dp[i][0] = 1; result = 1; } for(int j = 0; j < col; j++) if(matrix[0][j] == '1'){ dp[0][j] = 1; result = 1; } for(int i = 1; i < row; i++){ for(int j = 1; j < col; j++){ if(matrix[i][j] == '1'){ dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; result = max(result, dp[i][j]); } } } return result * result; } };class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.empty() || matrix[0].empty()) return 0; int row = matrix.size(); int col = matrix[0].size(); vector<vector<int> > dp(row, vector<int>(col, 0)); int result = 0; for(int i = 0; i < row; i++) if(matrix[i][0] == '1'){ dp[i][0] = 1; result = 1; } for(int j = 0; j < col; j++) if(matrix[0][j] == '1'){ dp[0][j] = 1; result = 1; } for(int i = 1; i < row; i++){ for(int j = 1; j < col; j++){ if(matrix[i][j] == '1'){ dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; result = max(result, dp[i][j]); } } } return result * result; } };
相关文章推荐
- 经济--如何买基金?
- 顺序容器和关联容器添加新元素方法详解
- iOS 对象信息保存、转化JSON、JSON生成对象的模型方案记录
- Java中的栈:java.util.Stack类
- virtualenv简单使用
- win2008阿里一键环境包mysql老是1067报错
- Unity3D图片质量设置
- 插入排序(折半插入)
- 用python做了一个 qq炫舞 机器人
- libgdx API之AI:AI让游戏对象思考
- Unity优化技巧提到的3篇翻墙文章之Unity 4.3 關於 Occlusion Culling : 錯誤診斷
- 京城码帮——不做单纯的程序员,第二次聚会总结
- 选择排序(直接选择)
- dojo/dom-construct.toDom方法学习笔记
- webwork+spring+hibernate进行数据增删查改操作时出现NullPointerException异常
- Linux系统管理之LVM逻辑卷管理
- 数据存储
- Finder增强插件XtraFinder
- Unity优化技巧提到的3篇翻墙文章之Unity 4.3 關於 Occlusion Culling : 最佳做法
- Unity优化技巧提到的3篇翻墙文章之Unity 4.3 關於 Occlusion Culling : 基本篇