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 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;
    }
};

你可能感兴趣的:(LeetCode,dp,Matrix)