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++
#include <bits/stdc++.h>
using namespace std;
int minimum_Moves( int x, int y)
{
if (x < y)
return -1;
else
return x;
}
int main()
{
long long int X2 = 47, Y2 = 11;
printf ( "%d" , minimum_Moves(X2, Y2));
}
|
C
#include <stdio.h>
int minimum_Moves( int x, int y)
{
if (x < y)
return -1;
else
return x;
}
int main()
{
long long int X2 = 47, Y2 = 11;
printf ( "%d" , minimum_Moves(X2, Y2));
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static long minimum_Moves( long x, long y)
{
if (x < y) {
return - 1 ;
}
else {
return x;
}
}
public static void main (String[] args)
{
long X2 = 47 , Y2 = 11 ;
System.out.println(minimum_Moves(X2, Y2));
}
}
|
Python
def minimum_Moves(x, y):
if (x < y):
return - 1
else :
return x
X2 = 47
Y2 = 11
print (minimum_Moves(X2, Y2))
|
C#
using System;
class GFG {
static int minimum_Moves( int x, int y)
{
if (x < y) {
return -1;
}
else {
return x;
}
}
public static void Main()
{
int X2 = 47, Y2 = 11;
Console.WriteLine(minimum_Moves(X2, Y2));
}
}
|
Javascript
<script>
function minimum_Moves(x, y)
{
if (x < y)
{
return -1;
}
else
{
return x;
}
}
let X2 = 47, Y2 = 11;
document.write(minimum_Moves(X2, Y2) + '<br>' );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)