美文网首页
221. Maximal Square

221. Maximal Square

作者: HalcyonMoon | 来源:发表于2016-06-29 16:23 被阅读0次

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 BFS(char[][] matrix, int i, int j, int len, int wid) {
        int ret = 1;
        for (int k = 1; k < Math.min(len - i, wid - j); k++) {
            for (int g = 0; g <= k; g++) {
                if (matrix[i + k][j + g] == '0' || matrix[i + g][j + k] == '0') {
                    return k * k;
                }
            }
            ret = (k + 1) * (k + 1);
        }
        return ret;
    }
    
    public int maximalSquare(char[][] matrix) {
        int len = matrix.length;
        if(len == 0){
            return 0;
        }
        int wid = matrix[0].length;
        int ret = 0;

        for(int i = 0; i<len; i++){
            for(int j = 0; j<wid; j++){
                if(matrix[i][j] == '1'){
                    ret = Math.max(ret, BFS(matrix, i, j, len, wid));
                }
            }
        }
        
        return ret;
    }
}

相关文章

网友评论

      本文标题:221. Maximal Square

      本文链接:https://www.haomeiwen.com/subject/omrxjttx.html