Maximal Square
2015-10-04 10:19
274 查看
原题链接
题目
思路
code
题目
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.
思路
1 可以直接暴露解决, 时间复杂度O(n^3) 2 dp方法: 使用动态规划优化到O(n^2),下面的代码12ms AC。构造一个新的矩阵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; 对于题目所给的例子就有: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 转化成: 1 0 1 0 0 1 0 1 1 1 1 1 1 2 1 1 0 0 1 0
code
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m <= 0) return 0; int n = matrix[0].size(); vector<vector<int> > dp(m + 1, vector<int>(n + 1, 0)); // the max edge length int maxlen = 0; for(int i = 1; i <= m; i++) { for(int j = 1; j <= n; j++) { if(matrix[i - 1][j - 1] == '0') dp[i][j] = 0; else { dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; maxlen = max(maxlen, dp[i][j]); } } } return maxlen * maxlen; } };
相关文章推荐
- C#使用Matrix执行缩放的方法
- 如何使用Matrix对bitmap的旋转与镜像水平垂直翻转
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- HP Z800 Workstation - Configuring RAID devices (HP Z800 做磁盘Raid1,Raid0的阵列)
- Android px、dp、sp之间相互转换
- Android Matrix类以及ColorMatrix类详解
- 用css实现图片的旋转
- 让舞台上的按钮btn灰掉
- Android中Bitmap和Drawable
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum