LeetCode 221. Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1
1 1 11 1
1 0 0 1 0

Return 4.
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(matrix.size()==0) return 0;
        int len=0;
        for(int i=0; i<matrix.size(); i++)
            if(matrix[i][0]=='1')
               len=1;
        for(int i=0; i<matrix[0].size(); i++)
            if(matrix[0][i]=='1')
                len=1;
        for(int i=1; i<matrix.size(); i++)
            for(int j=1; j<matrix[0].size(); j++){
                if(matrix[i][j]!='0'){
                    matrix[i][j]='0'+(min(matrix[i-1][j]-'0',min(matrix[i][j-1]-'0',matrix[i-1][j-1]-'0'))+1);
                    len=max(len,matrix[i][j]-'0');
                }  
            }
        return len*len;       
    }
};
posted @ 2018-12-03 15:09  A-Little-Nut  阅读(126)  评论(0编辑  收藏  举报