Algorithm title: Maximum Rectangle _ algorithm in histogram and 0-1 matrix

Source: Internet
Author: User

A few days ago to see an algorithm topic, it looks very simple, that is, there is a rectangle composed of 0 and 1, and then find the rectangle of all elements are 1 of the largest rectangular rectangle, it seems quite simple at first, but I think half a day did not think out. Search on the Internet to find that the topic is quite famous, many people have written articles discussed, a very good solution is to borrow a histogram to find the largest area of the rectangle algorithm, you can use a very short code to achieve. So I am prepared to account for the two problems of the solution, have some of their own perspective for reference. Find the largest rectangle in the histogram

The title of this question is as follows:
Given n non-negative integers representing the histogram ' s bar height where the width of each bar are 1, find the area of L Argest rectangle in the histogram.

Above is a histogram where width to each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown into the shaded area and which has area = ten unit.

Here's a quick way to get to O (N) by using a stack solution. 1

First, consider an extreme case where all the elements are ascending.

In this case, how do we find the largest rectangle. Here first introduce a method, we will see that he is able to work.

Step: First look at the rightmost is the largest rectangle, the largest rectangle that it can make is itself, and then consider the second last, the largest rectangle it can make is its own area multiplied by 2 (assuming the width of the rectangle is 1, the drawing is not standard), i.e. (maximum position I-current rectangular position k+1)
As shown in the following figure

And so on, and so on until the smallest rectangle, the maximum size of all the resulting area is the required area. The correctness of this algorithm is obvious.

With the above extreme situation in the matting, we understand that the real algorithm is much simpler.

In the complete algorithm, we need to use the stack of this data structure, corresponding to the above situation, the stack is full after the continuous pop (), on the corresponding and from the rightmost to the left of the calculation process. However, the problem is obvious, what to do if the situation is not in ascending order. It is also simple, we have to turn the problem into a known problem, there is no ascending situation, we construct this situation:

Observe the above situation, I follow the logic of the algorithm to go through, first I will 0 into the stack (where the operation is the number of rectangles), and then compare the size of the 1th rectangle and No. 0, the result is larger than it, then 1 pressure into the stack, and so on. Assuming it is now the turn to operate the fifth rectangle, it turns out that 5th is smaller than 4th. So first the 4th rectangle will not be able to and the right side of the rectangle to form a larger rectangle, he can form the largest rectangle is its own, so you can pop it out of the tube, it can be understood that we need to keep the "tall" rectangle ejected, Let the remaining rectangles in the stack form a set of ascending rectangles with the 5th rectangle, which is still outside, and then continue to add new elements until all the rectangles are added, if all the rectangles are pressed into the stack inside the stack. That's right. All the rectangles that correspond to the ordinal numbers are ascending. , and then we'll be able to handle all the rectangles according to the ascending classic. But it seems to be a bit wrong, some rectangles pop up, the final calculation of the result is wrong. is right. Also look at the picture above, assuming that only these 6 rectangles, when we want to add 5, we found that the situation is not right, so the number 4th and 3rd are ejected continuously, these two can calculate the largest rectangle, and then the 2nd rectangle is smaller than 5th, then put 5th into the stack, then there is no, then 5th the largest rectangle is its own, the number 2nd, By serial number (area of 2nd (5-2+1)). 3, 42 rectangles although pop-up, but the effect of the serial number is still, also ensure the correctness of the final result. There is also a special case is that the last pop-up stack of the rectangle must be the smallest, so its area multiplied by the total number of rectangles on the line.

It can be seen that this algorithm on the entire rectangle height of the array, a push, a pop-up, so the total time cost is O (N), the code is placed in the back, the principle is the same as above, but the specific serial number aspects of a little difference. The largest rectangle in the 0-1 matrix

0 0 1 1 0-> 0 0 1 1 0
0 0 1 1 0-> 0 0 2 2 0
1 1 0 0 0-> 1 1 0 0 0
1 1 1 0 0-> 2 2 1 0 0

How to find the largest rectangle, as the rectangle on the left figure above. , with the above algorithm, the problem is much simpler, we first do a processing of the rectangle, the first line unchanged, starting from the second line, if an element of 0, that will not change, not 0, it becomes the above element plus 1. The overall effect is to count the number of consecutive 1 from the beginning. Then the algorithm for the largest contiguous rectangle in the histogram is run on each row of the processed rectangle, so it is obvious that the maximum rectangle of the whole matrix can be obtained after all the rows have been calculated with the largest contiguous rectangle at the bottom of the action. The easy to know time cost is O (MN).

Here is the Java code:

public class Rectanglesolution {public int largestrectanglearea (int[] height) {if (height.length==0) return 0
        ;
        stack<integer> stack = new stack<integer> ();
        int I=1, max = height[0];

        Stack.push (0); while (i< height.length| | (i==height.length&&!stack.isempty ())) {if (i!=height.length && stack.isempty () | |
                Height[i] >= Height[stack.peek ())) {Stack.push (i);
            i++;
                else {int top = Height[stack.pop ()]; int currmax =!stack.isempty ()?
                Top * (I-stack.peek ()-1): Top *i;
            max = Math.max (Currmax, Max);
    } return max;
        public int maximalrectangle (int[][] rec) {int[] h = new Int[rec[0].length];
        int m = rec.length;
        int n = rec[0].length;
        int max=0;
               for (int i=0;i<m;i++) {for (int j=0;j<n;j++) { if (i==0) h[j] =rec[i][j]; else h[j] = rec[i][j]==0?
            0:rec[i-1][j]+1;

        max = Math.max (max, Largestrectanglearea (h));

    return to Max; public static void Main (string[] args) {int[][] rec = {{0,0,1,1,0,1},{0,0,1,1,0,1},{1,1,0,0,0,1},{1,1,1,0
        , 0,1},{1,1,1,0,0,1}};
        int[] Test ={2,2,1,0,0};
        Rectanglesolution rsolution = new Rectanglesolution ();
        int max = Rsolution.maximalrectangle (rec);
        int max2 = Rsolution.largestrectanglearea (test);
        SYSTEM.OUT.PRINTLN (max);



    System.out.println (MAX2); }


}

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.