C语言 有两个矩形 求重叠面积,计算两个矩形重叠面积的简单方法

实验需要,需要计算两个矩形重叠面积

想来想去觉得挺复杂,搜了下,看见一个超给力的方法

这里分享下:

function D = DecideOberlap(Reframe,GTframe)

x1 = Reframe(1);

y1 = Reframe(2);

width1 = Reframe(3);

height1 = Reframe(4);

x2 = GTframe(1);

y2 = GTframe(2);

width2 = GTframe(3);

height2 = GTframe(4);

endx = max(x1+width1,x2+width2);

startx = min(x1,x2);

width = width1+width2-(endx-startx);

endy = max(y1+height1,y2+height2);

starty = min(y1,y2);

height = height1+height2-(endy-starty);

if width<=0||height<=0

D = 0;

else

Area = width*height;

Area1 = width1*height1;

Area2 = width2*height2;

ratio = Area/(Area1+Area2-Area);

if ratio>=0.5

D = 1;

else

D = 0;

end

endratio就是计算出来的重叠率

函数中的两个参数分别是两个矩形的左上角点的坐标和矩形长,宽。

代码效率很高,写成c也很容易

以下是非递归实现柱状图最大矩形面积的C语言代码: ```c #include <stdio.h> #include <stdlib.h> #include <limits.h> // 定义栈结构体 typedef struct { int top; // 栈顶指针 int* arr; // 存储栈元素的数组 } Stack; // 创建一个栈 Stack* create(int size) { Stack* s = (Stack*)malloc(sizeof(Stack)); s->top = -1; s->arr = (int*)malloc(sizeof(int) * size); return s; } // 判断栈是否为空 int isEmpty(Stack* s) { return s->top == -1; } // 判断栈是否已满 int isFull(Stack* s, int size) { return s->top == size - 1; } // 入栈 void push(Stack* s, int x) { s->arr[++s->top] = x; } // 出栈 int pop(Stack* s) { return s->arr[s->top--]; } // 获取栈顶元素 int peek(Stack* s) { return s->arr[s->top]; } // 最大矩形面积 int largestRectangleArea(int* heights, int heightsSize) { Stack* s = create(heightsSize + 1); // 创建栈,栈的大小为 heightsSize + 1 int maxArea = 0; // 最大矩形面积 int i = 0; // 遍历 heights 数组的指针 while (i < heightsSize || !isEmpty(s)) { if (isEmpty(s) || heights[i] >= heights[peek(s)]) { push(s, i++); // 如果栈为空或当前元素大于等于栈顶元素,将当前元素入栈 } else { int top = pop(s); // 如果当前元素小于栈顶元素,弹出栈顶元素 int width = isEmpty(s) ? i : i - peek(s) - 1; // 计算矩形宽度 int area = heights[top] * width; // 计算矩形面积 if (area > maxArea) { maxArea = area; // 更新最大矩形面积 } } } // 释放栈占用的内存 free(s->arr); free(s); return maxArea; } int main() { int heights[] = {2, 1, 5, 6, 2, 3}; int heightsSize = sizeof(heights) / sizeof(int); int maxArea = largestRectangleArea(heights, heightsSize); printf("最大矩形面积:%d\n", maxArea); return 0; } ``` 该算法的时间复杂度为O(n),空间复杂度为O(n),其中n为柱状图的高度数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值