Leetcode176: Maximal Square
来源:互联网 发布:contabs.js插件 编辑:程序博客网 时间:2024/05/21 11:14
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 0
Return 4.
用动态规划的思想,令res[i][j]表示以i,j为右下角坐标的正方形的最大边长,则 res[i][j] = min(min(res[i-1][j], res[i][j-1]), res[i-1][j-1])+1
class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m==0) return 0; int n = matrix[0].size(); if(n==0) return 0; vector<vector<int>> res(m, vector<int>(n)); int maxlen=0; for(int i = 0; i < m; i++) { if(matrix[i][0] == '1') { res[i][0] = 1; maxlen = 1; } } for(int i = 0; i < n; i++) { if(matrix[0][i] == '1') { res[0][i] = 1; maxlen = 1; } } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { if(matrix[i][j] == '1') { res[i][j] = min(min(res[i-1][j], res[i][j-1]), res[i-1][j-1])+1; maxlen = max(maxlen, res[i][j]); } else { res[i][j] = 0; } } } return maxlen*maxlen; }};
0 0
- Leetcode176: Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- Maximal Square
- MongoDB学习笔记(robomongo 数据查询)
- linux内核SPI总线驱动分析(一)
- 二叉树实现实验
- 平台服务端日志查看说明
- MongoDB学习笔记(robomongo 数据查询)
- Leetcode176: Maximal Square
- 工作经验总结
- Dlib机器学习库学习系列三----人脸对齐(特征点检测)
- 安卓ROOT权限代码
- C++——构造函数
- 获得100000+点击的程序员高薪职业建议!
- 如何查看ubi绑定到哪个设备
- hibernate eventes not mapped[HQL] exception
- PKI技术原理