标签:
Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.
题意:求0,1矩阵中,1构成的最大矩阵。
思路:借用了上一题,首先我们先计算出dp[i][j]表示到第i行第j列时,此时这一列的连续1的个数,然后计算每一行的时候,每一列都相当于一个直方图。
public class Solution { public int maximalRectangle(char[][] matrix) { int n = matrix.length; if (n == 0) return 0; int m = matrix[0].length; if (m == 0) return 0; int dp[][] = new int[n+1][m+1]; for (int i = 0; i < m; i++) if (matrix[0][i] == '1') dp[0][i] = 1; for (int j = 0; j < m; j++) for (int i = 1; i < n; i++) if (matrix[i][j] == '1') dp[i][j] = dp[i-1][j] + 1; int ans = 0; for (int i = 0; i < n; i++) { int tmp = largestRectangleArea(dp[i]); ans = Math.max(ans, tmp); } return ans; } public int largestRectangleArea(int[] height) { Stack<Integer> stack = new Stack<Integer>(); int i = 0; int ans = 0; int h[] = new int[height.length+1]; h = Arrays.copyOf(height, height.length+1); while (i < h.length) { if (stack.isEmpty() || h[stack.peek()] <= h[i]) stack.push(i++); else { int t = stack.pop(); ans = Math.max(ans, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1)); } } return ans; } }
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45008099