LeetCode 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.

class Solution {

public:

    int maximalSquare(vector<vector<char>>& matrix) {

        int rows = matrix.size();

        if (rows < 1) {

            return 0;

        }

        int cols = matrix[0].size();

        if (cols < 1) {

            return 0;

        }

        

        vector<int> dp0(cols + 1, 0);

        vector<int> dp1(cols + 1, 0);

        

        int dlen = 0;

        for (int i=1; i<=rows; i++) {

            for (int j=1; j<=cols; j++) {

                if (matrix[i-1][j-1] == '0') {

                    dp1[j] = 0;

                } else {

                    dp1[j] = min(dp1[j-1], min(dp0[j], dp0[j-1])) + 1;

                }

                dlen = max(dlen, dp1[j]);

            }

            swap(dp0, dp1);

        }

        return dlen * dlen;

    }

};

dp写起来爽,想起来不爽

 

你可能感兴趣的:(LeetCode)