Leetcode Maximal Rectangle

Source: Internet
Author: User

Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest rectangle containing all ones and return to its area.

Test instructions: To find the largest matrix in the 0,1 matrix, 1.

Idea: Borrowed the previous question, first we calculate the dp[i][j] in row I, when the column J column, at this time the number of consecutive 1, and then calculate each row, each column is equivalent to a histogram.

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; }  }



Leetcode Maximal Rectangle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.