Leetcode 221. Maximal Square
2017-07-08 19:11
295 查看
问题描述
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:
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
问题分析:
题目要求求出全部是1的正方形的面积,要求正方形的面积,只需知道边长即可。
设数组dp[i][j]表示正方形右下角的最大正方形的边长,所以有状态转移方程:
dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]);
代码如下:
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 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
问题分析:
题目要求求出全部是1的正方形的面积,要求正方形的面积,只需知道边长即可。
设数组dp[i][j]表示正方形右下角的最大正方形的边长,所以有状态转移方程:
dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]);
代码如下:
public int maximalSquare(char[][] matrix) { int n=matrix.length; if(n<=0) return 0; int m=matrix[0].length; int[][]dp=new int [m]; int result=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[i][j]=matrix[i][j]-'0'; if(i>0&&j>0&&dp[i][j]>0){ dp[i][j]=Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]))+1; } if(dp[i][j]>result) result=dp[i][j]; } } return result*result; }
相关文章推荐
- Leetcode 221. Maximal Square
- LeetCode 85. Maximal Rectangle&221. Maximal Square--动态规划
- **Leetcode 221. Maximal Square | dp
- leetcode 221. Maximal Square & 85. Maximal Rectangle
- Leetcode 221. Maximal Square
- [LeetCode]--221. Maximal Square
- [leetcode] 221. Maximal Square 解题报告
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- [LeetCode] 221. Maximal Square 最大正方形
- 【Leetcode】221. Maximal Square
- Leetcode 221. Maximal Square
- Leetcode 221. Maximal Square
- LeetCode 221. Maximal Square(最大正方形)
- Leetcode 221. Maximal Square
- leetcode 221. Maximal Square
- leetcode题解分析_221. Maximal Square(图文分析)
- LeetCode221. Maximal Square
- 求解最大正方形面积 — leetcode 221. Maximal Square
- Leetcode 221. Maximal Square 单调队列和dp两种思路求解