Find all rectangles in the histogram

I'm sure most of you have heard of the biggest rectangle in the histogram problem. - Link -

In my current project, I need to modify this algorithm to detect all rectangles that are not a smaller subset of the other rectangle in this histogram.

That's how far I am now. But I can’t figure out how to disregard the subsets here.

   //time: O(n), space:O(n)
     public ArrayList<int[]> largestRectangles(int[] height) {
            ArrayList<int[]> listRect = new ArrayList<int[]>();

            if (height == null || height.length == 0) {
                return null;
            }

            Stack<Integer> stack = new Stack<Integer>();

            int max = 0;
            int i = 0;

            while (i < height.length) {
                //push index to stack when the current height is larger than the previous one
                if (stack.isEmpty() || height[i] >= height[stack.peek()]) {
                    stack.push(i);
                    i++;
                } else {
                //add rectangle when the current height is less than the previous one
                    int p = stack.pop();
                    int h = height[p];
                    int w = stack.isEmpty() ? i : i - stack.peek() - 1;
                    listRect.add(new int[]{p,h,w});
                }

            }

            while (!stack.isEmpty()) {
                int p = stack.pop();
                int h = height[p];
                int w = stack.isEmpty() ? i : i - stack.peek() - 1;
                listRect.add(new int[]{p,h,w});
            }

            return listRect;
        }
public static void main(String[] args) {

         for(int[] rect : largestRectangles(new int[]{1,2,2,3,3,2})) {
             System.out.print("pos:"+rect[0]+" height"+rect[1]+" 
         width"+rect[2]);
             System.out.println();
         }
     }
+4
source share
1 answer

, , , ; , ( ). Java IDE, #.

, (, java) Rect.Add(new [] {p, h, w}.).

if (listRect.Count > 0)
{

    if (listRect[listRect.Count - 1][1] <= h)
    {
        listRect.RemoveAt(listRect.Count - 1);
    }
}

. 0 , .. New int [] {1, 2, 2, 3, 3, 2, 0, 1} .. ; .. .

+1

Source: https://habr.com/ru/post/1692471/


All Articles