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.

 

题解来自 http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/

反正我觉得是好聪明,俺想不出来

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[][]
public class Solution {

    public int maximalSquare(char[][] matrix) {

        if(matrix==null||matrix.length==0||matrix[0].length==0) return 0;

        int m = matrix.length;

        int n = matrix[0].length;

        int[][] s = new int[m][n];

        

        for(int i=0;i<m;i++){

            if(matrix[i][0]=='1')

                s[i][0]=1;

        }

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

            if(matrix[0][j]=='1')

                s[0][j]=1;

        }

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

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

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

                    s[i][j] = Math.min(Math.min(s[i-1][j-1],s[i][j-1]),s[i-1][j])+1;

                }else

                    s[i][j] = 0;

            }

        }

        int res =s[0][0];

        for(int i=0;i<m;i++){

            for(int j=0;j<n;j++){

                res = Math.max(res,s[i][j]);

            }

        }

        return  res*res ;

    }

}

 

你可能感兴趣的:(max)