Leetcode: Maximal Square
2015-09-12 13:54
176 查看
Question
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Hide Tags Dynamic Programming
Hide Similar Problems
Solution
Get idea from here[code]class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if matrix==None or len(matrix)==0: return 0 m, n = len(matrix), len(matrix[0]) dp = [[0]*n for dummy in range(m)] res = 0 for ind in range(m): dp[ind][0] = 1 if matrix[ind][0]=='1' else 0 if dp[ind][0]>res: res = dp[ind][0] for ind in range(n): dp[0][ind] = 1 if matrix[0][ind]=='1' else 0 if dp[0][ind]>res: res = dp[0][ind] for mind in range(1,m): for nind in range(1,n): if matrix[mind][nind]=='1': dp[mind][nind] = min([ dp[mind-1][nind], dp[mind][nind-1], dp[mind-1][nind-1] ]) + 1 if dp[mind][nind]>res: res = dp[mind][nind] else: dp[mind][nind] = 0 return res**2
相关文章推荐
- php---mysql+ajax 无序列表(ul li)分页实现
- #1165 : 益智游戏
- C++中栈区 堆区 常量区
- igrimaceV8.0.0 IG 一键新机 陌陌 Uber优步打针 平安易贷 滴滴 一号专车 饿了么 ios8 V8 ZTN(插件安装方式)
- 函数指针
- Linux下MySql忘记 root密码的解决办法
- leetcode 刷道题 70 earch Insert Position 二进制搜索插入位置
- 2015年9月12日模拟赛总结
- EJB杂项
- State模式及与Strategy/Commmand/Chain of Resposibility区别
- Android Notification (转)
- 你见过最好的幼儿园
- (二)我的JavaScript系列:JavaScript面向对象旅程(下)
- 网页布局基础
- 浅谈.net remoting 与webservice
- iOS 裁剪图片
- C/C++常用头文件及函数汇总
- 第二周项目三—体验复杂度(2)
- Tian Ji -- The Horse Racing 2287 (好题 数学逻辑)
- 浅谈Android的三种数据持久化技术之文件存储