Closest Loot Box- Editorial || LOOT

PROBLEM LINK:

Problem Code: LOOT

Practise: Closest Loot Box

Contest :Campus Code

Author: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9
Tester: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9
Editorialist: Codechef Adgitm Chapter : https://www.codechef.com/users/test_account_9

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Basic Looping, basic Input Output

PROBLEM:

Given the position of all the loot boxes and your current position, find the closest lootbox to you in terms of Manhattan distance.
That is, you can move around forward, backwards, left, and right, but not diagonally. If there are multiple possible closest lootboxes, return any of them.

EXPLANATION:
The loot box whose x and y coordinates are closest to x and y coordinates of the current position is the closest loot box.
Therefore, if x1, y1 are the x and y coordinates of the current position and x and y are the x and y coordinates of lootbox then we need to find the loot box whose |x1 - x| + |y1-y| is the smallest.
Also, the question does not specify how many lootboxes are there, so for c++, we can use the fact that std::cin returns true if there is a value to input and returns false if there is no value left to input. For Python or java, we can use exception handling.

SOLUTION:
C++:
#include
using namespace std;

int main() {
int x1, y1;
cin>>x1>>y1;
int shortestDistance = 100000;
int ansX = 0, ansY = 0;
while(true){
int x, y;
if(cin>>x && cin>>y) {
if(shortestDistance > abs(x1-x) + abs(y1-y)){
shortestDistance = abs(x1-x) + abs(y1-y);
ansX = x;
ansY = y;
}
}else break;
}

cout<<ansX<<" "<<ansY<<endl;

return 0;

}