
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Find Total Time to Pull the Box by Rabbit
Suppose we have two coordinates (x1, y1) and (x2, y2). A rabbit is pulling food box. He is attached with a rope with only 1 unit sized rope. Rabbit will pull the box to where it is standing before moving out of the way in the same direction by 1 unit. Rabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for it to be in exactly 1 unit away from the box. If he wants to pull the box again, it must go to a point next to the box. Rabbit can start at any point. It takes 1 second to travel 1 unit at any direction. We have to find the minimum amount of time it needs to move the box from start location to end location.
So, if the input is like x1 = 1; y1 = 1; x2 = 2; y2 = 2, then the output will be 4, because Rabbit can start at the point (2,1). It pulls the box to (2,1) while it is in (3,1). Then moves to (3,2) and then to (2,2) without pulling the box. Then, pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.
Steps
To solve this, we will follow these steps −
s := 0 if x1 is not equal to x2 and y1 is not equal to y2, then: s := |x2 - x1| + |y2 - y1| Otherwise s := |x2 - x1| + |y2 - y1| return s
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(int x1, int y1, int x2, int y2){ int s = 0; if (x1 != x2 && y1 != y2) s = abs(x2 - x1) + abs(y2 - y1) + 2; else s = abs(x2 - x1) + abs(y2 - y1); return s; } int main(){ int x1 = 1; int y1 = 1; int x2 = 2; int y2 = 2; cout << solve(x1, y1, x2, y2) << endl; }
Input
1, 1, 2, 2
Output
4