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.

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix.length == 0||matrix[0].length ==0) return 0;
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] size = new int[m][n];
        int maxsize = 0;
        for(int j = 0; j < n; j++){
            size[0][j] = matrix[0][j] - '0';
            maxsize = Math.max(maxsize,size[0][j]);
        }
        for(int i = 1; i < m; i++){
            size[i][0] = matrix[i][0] - '0';
            maxsize = Math.max(maxsize,size[i][0]);
        }
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                if(matrix[i][j] == '1'){
                    size[i][j] = Math.min(size[i-1][j-1],Math.min(size[i-1][j],size[i][j-1]))+1;
                    maxsize = Math.max(maxsize,size[i][j]);
                }
            }
        }
        return maxsize * maxsize;
    }
}

https://leetcode.com/discuss/38489/easy-solution-with-detailed-explanations-8ms-time-and-space

詳細總結博客



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章