LeetCode Maximal Square

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

For example, given the following matrix:


使用动态规划的方式可以非常好的进行处理

java

public class Solution {
    /**
     * @param matrix: a matrix of 0 and 1
     * @return: an integer
     */
    public int maxSquare(int[][] arr) {
        // write your code here
        if (arr == null || arr.length == 0 || arr[0] == null || arr[0].length == 0) {
            return 0;
        }
        int[][] f = new int[arr.length][arr[0].length];
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            f[i][0] = arr[i][0];
            max = Math.max(max, arr[i][0]);
        }
        for (int i = 0; i < arr[0].length; i++) {
            f[0][i] = arr[0][i];
            max = Math.max(max, arr[0][i]);
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = 1; j < arr[i].length; j++) {
                if (arr[i][j] == 1) {
                    f[i][j] = Math.min(f[i - 1][j], Math.min(f[i][j - 1], f[i - 1][j - 1])) + 1;
                } else {
                    f[i][j] = 0;
                }
                max = Math.max(max, f[i][j]);
            }
        }
        return max * max;
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_32547403/article/details/79971525