直方图中最大的矩形

时间:2017-10-20 16:02:18

标签: c arrays function stack

我正在尝试编写一个代码来计算直方图中最大矩形的面积及其顶部坐标。 为了这个目的,我正在使用堆栈,以便在每个栏的情况下左右两侧的小栏。

根据GeeksForGeeks文章的指导,我遵循以下步骤:

" 1)创建一个空堆栈。

2)从第一个栏开始,并对每个栏'hist [i]'执行以下操作,其中'i'从0变为n-1。 ...... a)如果堆栈为空或hist [i]高于堆栈顶部的栏,则按“i”进行堆叠。 ...... b)如果此条小于堆栈顶部,则在堆栈顶部较大时继续移除堆栈顶部。让删除的条为hist [tp]。用hist [tp]作为最小条计算矩形区域。对于hist [tp],'left index'是堆栈中的前一个(tp之前)项,'right index'是'i'(当前索引)。

3)如果堆栈不为空,则逐个从堆栈中移除所有条形,并为每个移除的条形做步骤2.b。"

但我的代码给了我一些任意大的值,怀疑是地址值。  请帮我调试。

这是我的代码:`

#include <stdio.h>
#include <stdlib.h>

void maxRectangle(int hist[], int n);
void push(int stack[],int item,int *top,int n);
int pop(int stack[],int *top);
int peek(int stack[],int *top);
int isEmpty(int top);
int isFull(int top,int n);
void display(int stack[],int top);
int main()
{

    int n,i;
    printf("How many bars do you want to enter in the histogram?\n");
    scanf("%d",&n);

    int hist[n];
    printf("enter the hights of the consecutive bars\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&hist[i]);
    }

    maxRectangle(hist,n);
    return 0;
}

void maxRectangle(int hist[], int n)
{

    int top=-1;
    int i;
    int x1,y1,x2,y2;
    int max_area,idx, top_area;
    int stack[n];
    int bar=stack[top];

    while(i<n)
    {
    if(isEmpty(top)||(hist[bar]<hist[i]))
    {
        push(stack,i,&top,n);i++;
    }
    else
    {
        idx=peek(stack,&top); //smaller idx to the right
        pop(stack,&top); //bar idx  to compute the area for
        top_area= hist[idx]*(isEmpty(top)?i:i-peek(stack,&top)-1); //top(stack)is the smaller bar to the left
        if(top_area<max_area)
        {
            max_area=top_area;
            x1=(peek(stack,&top)+1);
            x2=idx+1;
            y1=y2=hist[idx];
        }
    }



    }

    printf("the largest area is %d, the top left coordinate is (%d,%d) and top-right coordinate is (%d,%d)\n",max_area,x1,y1,x2,y2);
}
void push(int stack[],int item,int *top,int n)
{
    if(isFull(*top,n))
    {
        printf("stack overflow!!\n");
        return;
    }
    *top=*top+1;
    stack[*top]=item;
}
int pop(int stack[],int *top)
{

    int item;
    if(isEmpty(*top))
    {
        printf("stack underflow!\n");
        exit(1);
    }
    item=stack[*top];
    *top=*top-1;
    return item;

}
int peek(int stack[],int *top)
{
    if(isEmpty(*top))
    {
        printf("stack underflow!");
        exit(1);
    }
    return stack[*top];
}
int isEmpty(int top)
{
    if(top==-1) return 1;
    else return 0;
}
int isFull(int top,int n)
{
    if(top==(n-1)) return 1;
    else return 0;
}

void display(int stack[],int top)
{
    int i;
    printf("stack elements are:\n\n");
    for(i=top;i>=0;i++)
    {
        printf("%d\n",stack[i]);
    }
    printf("\n");
}

`

1 个答案:

答案 0 :(得分:1)

这里有一些事情。

  1. int bar = stack[top];不好,因为top = -1
  2. 您的大多数变量都未初始化。这就是他们奇怪价值的原因。
  3. isEmpty(top)||hist[bar]<hist[i]将永远返回true,所以你只能推动。
  4. 如果你想要最大的区域,
  5. if(top_area<max_area)会倒退
  6. 还有其他较小的问题,但如果您修复这些问题,您的程序将正常运行。