Given a coordinate (x, y). The task is to calculate the number of steps required to reach point (x, y) from (0, 0) using zig-zag way and you cannot travel in straight line for more than 1 unit. Also, start moving along Y axis.
For example we can reach the Point denoted by red color in the respective ways as shown in the below diagram:
Input: x = 4, y = 4 Output: 8 In the diagram above the line is passing using 8 steps. Input: x = 4, y = 3 Output: 9 Input: x = 2, y = 1 Output: 5
Approach: By sketching a small diagram we can see the two cases:
- Case 1: If x is less than y then answer will always be x + y + 2*((y-x)/2).
- Case 2: If x is greater than equal to y then answer will always be x + y + 2*(((x-y)+1)/2).
Below is the implementation of the above approach:
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimize the number of steps required to reach the end of the array | Set 2
- Number of jump required of given length to reach a point of form (d, 0) from origin in 2D plane
- Lexicographically Kth smallest way to reach given coordinate from origin
- Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3
- Check if it is possible to reach (x, y) from origin in exactly Z steps using only plus movements
- Find the minimum number of steps to reach M from N
- Minimum steps to reach the Nth stair in jumps of perfect power of 2
- Minimum steps to reach N from 1 by multiplying each step by 2, 3, 4 or 5
- Count the minimum steps to reach 0 from the given integer N
- Minimize steps to reach K from 0 by adding 1 or doubling at each step
- Minimum steps for increasing and decreasing Array to reach either 0 or N
- Euler zigzag numbers ( Alternating Permutation )
- Length of the longest ZigZag subarray of the given array
- Minimum number of moves required to reach the destination by the king in a chess board
- Minimum number of steps required to obtain the given Array by the given operations
- Minimum time to reach a point with +t and -t moves at time t
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum steps to come back to starting point in a circular tour
- Probability of reaching a point with 2 or 3 steps at a time
- Rotation of a point about another point in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.