- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# 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

- Related Articles
- Find the minimum number of moves needed to move from one cell of matrix to another in Python
- How to find the minimum number of steps needed by knight to reach the destination using C#?
- Program to find number of optimal steps needed to reach destination by baby and giant steps in Python
- Program to find minimum number of rocketships needed for rescue in Python
- Program to find number of minimum steps to reach last index in Python
- Program to find lexicographically smallest string to move from start to destination in Python
- C++ program to find minimum how many operations needed to make number 0
- Program to find minimum number of steps required to catch the opponent in C++
- C++ program to count number of steps needed to make sum and the product different from zero
- C++ program to find minimum number of punches are needed to make way to reach target
- Find the minimum number of steps to reach M from N in C++
- C++ program to count minimum number of operations needed to make number n to 1
- Program to count number of paths with cost k from start to end point in Python
- Program to find minimum number of hops required to reach end position in Python
- Program to find minimum number of operations to move all balls to each box in Python

Advertisements