美文网首页
Maximal Square

Maximal Square

作者: BLUE_fdf9 | 来源:发表于2018-09-30 23:49 被阅读0次

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

    Example:

    Input:

    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0

    Output: 4

    答案

    class Solution {
        public int maximalSquare(char[][] matrix) {
            if(matrix == null || matrix.length == 0) return 0;
            int m = matrix.length, n = matrix[0].length;
            int[][] f = new int[m][n];
            
            int max = 0;
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(i == 0 || j == 0) {
                        f[i][j] = (matrix[i][j] == '1') ? 1:0;
                        max = Math.max(max, f[i][j]);
                        continue;
                    }
                    
                    int top = f[i - 1][j], left = f[i][j - 1], top_left = f[i - 1][j - 1];
                    f[i][j] = (matrix[i][j] == '1') ? Math.min(top, Math.min(left, top_left)) + 1 : 0;
                    max = Math.max(max, f[i][j]);
                }
            }
            return max * max;
        }
    }
    

    相关文章

      网友评论

          本文标题:Maximal Square

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