Search code examples
algorithmcoordinate-systems

Minimum number of moves to reach a point in a grid?


Starting from (0, 0) , I have to reach (x, y) in such a way that at any point I can move one step left/right if previous move was up/down and vice-versa. What is the minimum number of moves needed ?


Solution

  • according to the statement as every left-right movement must be followed an up-down move, and visa-versa, the following formula can give you the length of the shortest path.

    let us assume the x and y are positive distances what we need to walk in both direction, so

    x, y ∈ ℕ+ ⋃ {0}

    then

    steps = min (x, y) × 2 + 4 × floor (abs (x - y) / 2) + (x + y) mod 2

    where the

    • min (a, b) gives the smaller value of a and b, like min (1, 2) = 1;
    • floor (x) gives the whole part of x without fraction part, like floor(4.5) = 4;
    • abs(x) gives the positive distance of x from zero, like abs(-3) = abs(3) = 3;
    • x mod y gives the modulus (or remainder) of x / y, like 11 / 2 = 5 with remainder of 1;

    example:

    • in the case of (0, 10) the steps are 20;
    • in the case of (1, 10) the steps are 19;
    • in the case of (8, 5) the steps are 15;
    • in the case of (3, 3) the steps are 6;

    etc...