`

Leetcode - Maximum 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.

[分析]
思路1:修改MaxRectangle的实现,求解每一行上最大矩形面积改为求解最大正方形面积。
思路2:dp[i][j]表示以(i, j)为右下角顶点的正方形的边长,则(i, j)处为1时dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1

public class Solution {
    // Method 2: http://blog.csdn.net/xudli/article/details/46371673
    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int rows = matrix.length, cols = matrix[0].length;
        int max = 0;
        int[][] dp = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            dp[i][0] = matrix[i][0] == '1' ? 1 : 0;
            max = Math.max(max, dp[i][0]);
        }
        for (int j = 0; j < cols; j++) {
            dp[0][j] = matrix[0][j] == '1' ? 1 : 0;
            max = Math.max(max, dp[0][j]);
        }
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (matrix[i][j] == '1') {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
                    max = Math.max(max, dp[i][j]);
                }
            }
        }
        return max * max;
    }
    // Method 1: extension of maximalRectangle
    public int maximalSquare1(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int rows = matrix.length, cols = matrix[0].length;
        int[] h = new int[cols + 1];
        int max = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == '1')
                    h[j] += 1;
                else
                    h[j] = 0;
            }
            max = Math.max(max, getMaxSquare(h));
        }
        return max;
    }
    public int getMaxSquare(int[] h) {
        LinkedList<Integer> stack = new LinkedList<Integer>();
        int max = 0;
        for (int i = 0; i < h.length; i++) {
            while (!stack.isEmpty() && h[i] < h[stack.peek()]) {
                int currH = h[stack.pop()];
                while (!stack.isEmpty() && h[stack.peek()] == currH)
                    stack.pop();
                int len = Math.min(i - (stack.isEmpty() ? -1 : stack.peek()) - 1, currH);
                
                max = Math.max(max, len * len);
            }
            stack.push(i);
        }
        return max;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics