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 m = matrix.size();
	    if (m < 1)
	    {
		    return 0;
	    }
	    int n = matrix[0].size();
	    if (n < 1)
	    {
		    return 0;
	    }

	    vector<vector<int> > size(m, vector<int>(n, 0));
	    int maxSize = 0;
	    for (int i = 0; i < m; i++)
	    {
		    if (matrix[i][0] == '1')
		    {
			    size[i][0] = 1;
			    maxSize = 1;
		    }
	    }

	    for (int i = 0; i < n; i++)
	    {
		    if (matrix[0][i] == '1')
		    {
			    size[0][i] = 1;
			    maxSize = 1;
		    }
	    }

	    for (int i = 1; i < m; i++)
	    {
		    for (int j = 1; j < n; j++)
		    {
		        //size[i][j] 表示以matrix[i][j]为右下角,能形成全为1的正方形的长度。
			    if (matrix[i][j] == '1')
			    {
				    size[i][j] = min(size[i-1][j-1], 
				                     min(size[i-1][j], size[i][j-1])) + 1;
				    maxSize = max(maxSize, size[i][j]);
			    }
		    }
	    }

	    return maxSize*maxSize;
    }
};

你可能感兴趣的:(Maximal Square)