首页 > 代码库 > [LeetCode] Maximal Square
[LeetCode] Maximal Square
Maximal Square
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 0Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
解题思路:
最值问题考虑动态规划算法。设d[i][j]表示以matrix[i][j]为右下角的最慷慨阵大小,则有:
d[i][j] = 0; matrix[i][j]=‘0‘时
d[i][j] = 1; matrix[i][j]=‘1‘且(i==0||j==0)时
d[i][j] = pow(min(min(sqrt(d[i-1][j-1]), sqrt(d[i-1][j])), sqrt(d[i][j-1])) + 1, 2); 其它情况。
然后用一个变量maxSquare记录全局最大的方阵就可以。
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int n = matrix.size(); if(n==0){ return 0; } int m = matrix[0].size(); vector<vector<int>> d(n, vector<int>(m, 0)); //以matrix[i][j]为右下角的最慷慨阵大小 int maxSquare=0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(matrix[i][j]==‘0‘){ d[i][j] = 0; }else{ if(i>0&&j>0){ d[i][j] = (int)pow(min((int)min((int)sqrt(d[i-1][j-1]), (int)sqrt(d[i-1][j])), (int)sqrt(d[i][j-1])) + 1, 2); }else{ d[i][j] = 1; } maxSquare = max(maxSquare, d[i][j]); } } } return maxSquare; } };
[LeetCode] Maximal Square
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。