Middle-题目103:221. Maximal Square
来源:互联网 发布:怎样下载视频软件 编辑:程序博客网 时间:2024/06/04 17:57
题目原文:
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 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
题目大意:
给出一个0-1矩阵,求其中最大的由1组成的正方形,返回其面积。
题目分析:
还是Dp问题,设dp[i][j]为右下角为(i,j)的正方形的边长,则有如下转移方程:
初始化第一行(列)的dp[0][i]和dp[j][0]为矩阵的原值。
这个转移方程用文字比较难以描述,在纸上画一下三种情况就很好理解了。
源码:(language:java)
public class Solution { public int maximalSquare(char[][] matrix) { int row = matrix.length; if(row == 0) return 0; int col = matrix[0].length; int maxSquare = 0; int[][] dp = new int[row][col]; for(int i = 0 ;i<col;i++) { dp[0][i]=matrix[0][i]-'0'; if(matrix[0][i] == '1') maxSquare = 1; } for(int i = 0;i<row;i++) { dp[i][0]=matrix[i][0]-'0'; if(matrix[i][0] == '1') maxSquare = 1; } for(int i = 1;i<row;i++) { for(int j=1;j<col;j++) { if(matrix[i][j] == '1') dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[i-1][j-1], dp[i][j-1]))+1; if(dp[i][j] > maxSquare) maxSquare = dp[i][j]; } } return maxSquare*maxSquare; }}
成绩:
14ms,beats 58.15%,众数17ms,11.81%
0 0
- Middle-题目103:221. Maximal Square
- 题目: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
- 控制多行文本
- CSS3实现立体菜单
- VC中,使用ODBC 驱动连接Mysql
- Android 通过代码发送点击事件
- c++中的set_new_handler和new_handler
- Middle-题目103:221. Maximal Square
- 界面跳转(大牛勿喷,本人在开发中所认识到的小技巧)
- 安卓之创建,读写文件,本地收藏,访问文件的权限和产品测试种类(方法)
- linux环境搭建dubbo+zookeeper
- VS2010下Cannot find or open the PDB file
- 实现复数类中的运算符重载
- Java学习总结(16.05.31)Java位运算符
- 204. Count Primes
- 栈和堆最大可以申请的内存数