标签:
Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.
解题思路:
求01矩阵中,全是1的子矩阵的最大面积。
把矩阵按照每一行看做是直方图,可以转化为上一题,JAVA实现如下:
static public int maximalRectangle(char[][] matrix) { if(matrix.length==0||matrix[0].length==0) return 0; int result=0; int[] dp=new int[matrix[0].length]; for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++) if(matrix[i][j]==‘1‘) dp[j]++; else dp[j]=0; result=Math.max(result, largestRectangleArea(dp)); } return result; } public static int largestRectangleArea(int[] height) { Stack<Integer> stk = new Stack<Integer>(); int ret = 0; for (int i = 0; i <= height.length; i++) { int h=0; if(i<height.length) h=height[i]; if (stk.isEmpty() || h >= height[stk.peek()]) stk.push(i); else { int top = stk.pop(); ret = Math.max(ret, height[top] * (stk.empty() ? i : i - stk.peek() - 1)); i--; } } return ret; }
Java for LeetCode 085 Maximal Rectangle
标签:
原文地址:http://www.cnblogs.com/tonyluis/p/4515359.html