做题笔记6(判断矩形是否重叠)


一、题目

在这里插入图片描述

二、解决方案

1.直接法

1)代码

#include<iostream>
#include<stdio.h>
#include <iomanip>
#include<math.h>
using namespace std;
class Rect
{
private:
	int x1;
	int x2;
	int y1;
	int y2;
public:
	Rect(int a, int b, int c, int  d)
	{
		x1 = a;
		y1 = b;
		x2 = c;
		y2 = d;
	}
	int BigX()
	{
		if (x1 > x2)
		{
			return x1;
		}
		else
		{
			return x2;
		}
	}
	int BigY()
	{
		if (y1 > y2)
		{
			return y1;
		}
		else
		{
			return y2;
		}
	}
	int SmallY()
	{
		if (y1 < y2)
		{
			return y1;
		}
		else
		{
			return y2;
		}
	}
	int SmallX()
	{
		if (x1 < x2)
		{
			return x1;
		}
		else
		{
			return x2;
		}
	}
};
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int x1, y1, x2, y2;
		cin >> x1 >> y1 >> x2 >> y2;
		Rect a(x1, y1, x2, y2);
		cin >> x1 >> y1 >> x2 >> y2;
		Rect b(x1, y1, x2, y2);
		int w = 0;
		if (a.SmallY() < b.BigY())
		{
			if (a.SmallX() < b.BigX())
			{
				w = 1;
			}
			else if (a.BigX() > b.SmallX())
			{
				w = 1;
			}
		}
		else if (a.BigY() > b.SmallY() && a.SmallY() < b.SmallY())
		{
			if (a.SmallX() < b.BigX())
			{
				w = 1;
			}
			else if (a.BigX() > b.SmallX())
			{
				w = 1;
			}
		}
		if (w == 1)
		{
			cout << "overlapped" << endl;
		}
		if (w == 0)
		{
			cout << "not overlapped" << endl;
		}
	}
}

2)思路
采用分步判断,先判断关于y轴在重叠时的两种情况,再在每一次判断后加入关于x轴重叠两种情况的判断。

2.反向

1)代码


#include <iostream>
using namespace std;

typedef struct Rect {
	Rect(int x, int y, int width, int height)
		: x(x), y(y), width(width), height(height)
	{}
	int x;
	int y;
	int width;
	int height;
} Rect;

bool isOverlap(const Rect& rc1, const Rect& rc2)
{
	if (rc1.x + rc1.width > rc2.x &&
		rc2.x + rc2.width > rc1.x &&
		rc1.y + rc1.height > rc2.y &&
		rc2.y + rc2.height > rc1.y
		)
		return true;
	else
		return false;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int x1, y1, x2, y2;
		cin >> x1 >> y1 >> x2 >> y2;
		Rect rc1(x1, y1, x2, y2);
		cin >> x1 >> y1 >> x2 >> y2;
		Rect rc2(x1, y1, x2, y2);

		if (isOverlap(rc1, rc2))
			cout << "overlapped" << endl;
		else
			cout << "not overlapped" << endl;
	}
	return 0;
}

2)思路
先解决出不重叠的情况,再进行判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值