笔试题18——求两个矩形的交集

题目描述:
在屏幕坐标系(屏幕左上角是(0,0)点,向下y坐标增大,向右x坐标增大)定义矩阵rect,求两个矩形的交集(无交集时返回null)
输入描述:
输入两个矩形, x1 y1 w1 h1 x2 y2 w2 h2
输出描述:
交集的矩形(x y w h),无交集时输出null
示例输入:
0 0 200 200 100 100 100 100
输出:
100 100 100 100
重点是判断两个矩形相交的边界条件,核心代码如下:

#include <iostream>
using namespace std;

int main() {
	
	int a[4];
	int b[4];
	for (int i = 0; i < 4; i++) {
		cin >> a[i];
	}

	for (int i = 0; i < 4; i++) {
		cin >> b[i];
	}
	int x1 = a[0];  
	int x2 = a[0] + a[2];
	int y1 = a[1];
	int y2 = a[1] + a[3];
	
	int x3 = b[0];
	int x4 = b[0] + b[2];
	int y3 = b[1];
	int y4 = b[1] + b[3];

	if ((x3 >= x1 && x3 < x2) && (y3 >= y1 && y3 < y2)) {
		
		int w1 = x2 >= x4 ? x4 : x2;
		int h1 = y2 >= y4 ? y4 : y2;
		w1 -= x3;
		h1 -= y3;
		cout << x3 << " " << y3 << " " << w1 << " " << h1 << endl;
	}
	else if((x1 >= x3 && x1 < x4) && (y1 >= y3 && y1 < y4))
	{
		int w1 = x2 >= x4 ? x4 : x2;
		int h1 = y2 >= y4 ? y4 : y2;
		w1 -= x3;
		h1 -= y3;
		cout << x1 << " " << y1 << " " << w1 << " " << h1 << endl;
	}
	else
	{
		cout << "null" << endl;
	}
	return 0;
}
上一篇:LeetCode.1037-有效的回旋镖(Valid Boomerang)


下一篇:三门问题的怀疑