221. Maximal Square(难)
来源:互联网 发布:linux 替换jar包文件 编辑:程序博客网 时间:2024/06/09 15:58
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.
构造一个新的矩阵dp,dp[i][j]表示以点(i, j)为右下角的正方形的边长;状态转移方程:
dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;//注意min
对于题目所给的例子就有:
1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
转化成:
1 0 1 0 01 0 1 1 11 1 1 2 11 0 0 1 0
class Solution {public:int maximalSquare(vector<vector<char>>& matrix) {if (matrix.empty() || matrix[0].empty()) return 0;int r = matrix.size(),c = matrix[0].size();vector<vector<int>>dp(r, vector<int>(c, 0));int res = 0;for (int i = 0; i < r; i++){if (matrix[i][0]=='1'){dp[i][0] = 1;res = 1;}}for (int j = 0; j < c; j++){if (matrix[0][j] == '1'){dp[0][j] = 1;res = 1;}}for (int i = 1; i < r; i++){for (int j = 1; j < c; 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;if (dp[i][j]>res)res = dp[i][j];}}}return res*res;}};
0 0
- 221. Maximal Square(难)
- 221.Maximal Square
- [leetcode] 221.Maximal Square
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- leetcode 221. Maximal Square
- 221. Maximal Square LeetCode
- 221. Maximal Square
- 221. Maximal Square
- LeetCode 221. Maximal Square
- 221. Maximal Square
- LeetCode *** 221. Maximal Square
- 221. Maximal Square
- LeetCode-221.Maximal Square
- leetcode.221. Maximal Square
- 221. Maximal Square
- Leetcode 221. Maximal Square
- 221. Maximal Square
- oc学习之Foundation框架--NSSet类
- css动画
- 什么是Activity
- 面试问题汇总
- CodeForces 616A
- 221. Maximal Square(难)
- awk、cut、sort和uniq
- cocos2d-x-3.0学习笔记之如何添加菜单按钮
- python之显示按键操作
- M101P: MongoDB for Developers - Chapter 1: Introduction
- 【JZ雅礼联考】跳楼机 题解
- ListView复用导致checkBox错乱的解决方法
- Linux 共享库加载方法
- ConcurrentHashMap关于方法的深度解析