

Minimize moves to reach a target point from origin by moving horizontally or dia...
source link: https://www.geeksforgeeks.org/minimize-moves-to-reach-a-target-point-from-origin-by-moving-horizontally-or-diagonally-in-right-direction/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Minimize moves to reach a target point from origin by moving horizontally or diagonally in right direction
- Last Updated : 12 Jan, 2022
Given source (X1, Y1) as (0, 0) and a target (X2, Y2) on a 2-D plane. In one step, either of (X1+1, Y1+1) or (X1+1, Y1) can be visited from (X1, Y1). The task is to calculate the minimum moves required to reach the target using given moves. If the target can’t be reached, print “-1”.
Examples:
Input: X2 = 1, Y2 = 0
Output: 1
Explanation: Take 1 step from (X1, Y1) to (X1+1, Y1), i.e., (0,0) -> (1,0). So number of moves to reach target is 1.Input: X2 = 47, Y2 = 11
Output: 47
Naive Approach: The naive approach to solve this problem is to check all combination of (X+1, Y) and (X+1, Y+1) moves needed to reach the target and print the least among them.
Efficient Approach: Based on given conditions about movement, following points can be observed:
- If Y2 > X2, then we cannot the target since in every move it must that X increases by 1.
- If Y2 < X2, then we can either move diagonally Y2 times, and then (X2-Y2) times horizontally, or vice versa.
- If Y2 = X2, then we can move either X2 times diagonally or Y2 moves diagonally
The task can be solved using the above observations. If Y2 > X2, then the target can never be reached with given moves, else always a minimum of X2 moves are necessary.
Below is the implementation of the above approach-:
// C++ Implementation of the approach
#include <bits/stdc++.h>
using
namespace
std;
// Function to find minimum moves
int
minimum_Moves(
int
x,
int
y)
{
// If y > x, target can never be reached
if
(x < y) {
return
-1;
}
// In all other case answer will be X
else
{
return
x;
}
}
// Driver Code
int
main()
{
long
long
int
X2 = 47, Y2 = 11;
cout << minimum_Moves(X2, Y2) << endl;
}
47
Time Complexity: O(1)
Auxiliary Space: O(1)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK