Minimize moves to reach a target point from origin by moving horizontally or diagonally in right direction
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”.
Input: X2 = 1, Y2 = 0
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
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-:
Time Complexity: O(1)
Auxiliary Space: O(1)
Please Login to comment...