[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 01 0 1 1 11 1 1 1 11 0 0 1 0Return 4.

Credits:Special thanks to@Freezenfor 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

相关文章:

你感兴趣的文章:

标签云: