[LeetCode] 01矩阵中最大正方形 Maximal Square

相关问题1:[LeetCode] Find max subsquare whose border values are all 1

相关问题2:[LeetCode] 01矩阵中最大矩形 Maximal Rectangle

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.

思路:

假设给定是矩阵是 M ,可以构建一个大小一样的辅助矩阵S,具体构建规则如下:

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[][]
这样一来,S[ i ] [ j ] 就代表了以 M[ i ] [ j ] 为右下角的、最大的、全1 的 正方形的边长。

具体代码如下:

class Solution {
public:
    int maximalSquare(vector<vector<char>>& M) {
        
        int R = M.size();
        if(R==0) return 0;
        int C = M[0].size();
        if(C==0) return 0;
        
        int i,j;
        vector<vector<int>> S(R, vector<int>(C, 0) );
        int max_of_s, max_i, max_j;
        
        for(i = 0; i < R; i++)
            S[i][0] = M[i][0] - '0';
         
        for(j = 0; j < C; j++)
            S[0][j] = M[0][j] - '0';
        
        for(i = 1; i < R; i++)
        {
            for(j = 1; j < C; j++)
            {
                if(M[i][j] == '1')
                    S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1;
                else
                    S[i][j] = 0;
            }    
        } 
        
        max_of_s = S[0][0]; max_i = 0; max_j = 0;
        for(i = 0; i < R; i++)
        {
            for(j = 0; j < C; j++)
            {
                if(max_of_s < S[i][j])
                {
                    max_of_s = S[i][j];
                    max_i = i; 
                    max_j = j;
                }        
            }                 
        }     

        return max_of_s*max_of_s;
        
    }
 
 
    /* Function to get minimum of three values */
    int min(int a, int b, int c)
    {
        int m = a;
        if (m > b) 
            m = b;
        if (m > c) 
            m = c;
        return m;
    }
     
    
};


你可能感兴趣的:([LeetCode] 01矩阵中最大正方形 Maximal Square)