- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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++ program to find minimum number of steps needed to move from start to end
Suppose we have a coordinate (x, y). On a 2D grid, a robot is at (0, 0) position and want to reach (x, y). It can move up, down, left or right or stay at current cell. It wants to reach destination with as minimum as possible commands. We have to count the number of steps needed.
So, if the input is like x = 3; y = 4, then the output will be 7
Steps
To solve this, we will follow these steps −
return x + y + minimum of |x - y|, |x - y + 1|, and |x - y - 1|
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(int x, int y) { return x + y + min(abs(x - y), min(abs(x - y + 1), abs(x - y - 1))); } int main() { int x = 3; int y = 4; cout << solve(x, y) << endl; }
Input
3, 4
Output
7
Advertisements