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

解题思路

1) Construct a sum matrix S[R][C] for the given M[R][C].
 a) Copy first row and first columns as it is from M[][] to S[][]
 b) For other entries, use following expressions to construct S[][]
 If M[i][j] is 1 then
 S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
 Else /*If M[i][j] is 0*/
 S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print 
   sub-matrix of M[][]

更详细的解题思路见GeeksforGeeks。

实现代码

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if (matrix.empty())
        {
            return 0;
        }
        int row = matrix.size();
        int col = matrix[0].size();
        vector<vector<int>> s(row, vector<int>(col, 0));
        for (int i = 0; i < row; i++)
        {
            if (matrix[i][0] == '1')
            {
                s[i][0] = 1;
            }
        }

        for (int i = 0; i < col; i++)
        {
            if (matrix[0][i] == '1')
            {
                s[0][i] = 1;
            }
        }

        for (int i = 1; i < row; i++)
        {
            for (int j = 1; j < col; j++)
            {
                if (matrix[i][j] == '1')
                {
                    s[i][j] = min(s[i-1][j], min(s[i][j-1], s[i-1][j-1])) + 1;
                }
                else
                {
                    s[i][j] = 0;
                }
            }
        }

        int width = 0;
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                width = max(width, s[i][j]);
            }
        }

        return width * width;
    }
};

你可能感兴趣的:(LeetCode)