Thursday, June 24, 2021
Home coding Write a program to check if two rectangles overlap with each other?

Write a program to check if two rectangles overlap with each other?

Given a two rectangle having two coordinate bottom left and top right known so we have to find whether two rectangle overlap each other or not.

Example:

input:R1=(0,0,2,2)  R2=(1,1,3,3)
output:true

Logic:

Two rectangle will not overlap each other if any of the two condition will satisy:
1-one rectangle should be on the left edge of another rectangle.
2-one rectangle have to be on top of another rectangle.

Code-

#include<bits/stdc++.h> 
using namespace std;
struct coordinate
{ 
	int x, y; 
}; 

bool overlap(coordinate left1, coordinate right1, coordinate left2, coordinate right2) 
{ 
	if (left1.x >= right2.x || left2.x >= right1.x) //checking left side
		return false; 

	if (left1.y <= right2.y || left2.y <= right1.y) //checking top side
		return false; 

	return true; 
} 

int main() 
{ 
	coordinate left1 = {0, 10}, right1 = {10, 0}; 
coordinate left2 = {5, 5}, right2 = {15, 0}; 
	if (overlap(left1, right1, left2, right2)) 
	{
	    cout<<"reactangle overlap each other "<<endl;
	}
	else
	{
	    cout<<"rectangle will not able to each other"<<endl;
	}
	return 0; 
}

Output:

Rectangle will overlap each other.

Time complexity:0(N)

Space Complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments