Given a point (x, y), the task is to check if it is possible to reach from origin to (x, y) in exactly Z steps. From a given point (x, y) we can only moves in four direction left(x – 1, y), right(x + 1, y), up(x, y + 1) and down(x, y – 1).
Input: x = 5, y = 5, z = 11
Output: Not Possible
Input: x = 10, y = 15, z = 25
- The shortest path from origin to (x, y), is |x|+|y|.
- So, it is clear that if Z less than |x|+|y|, then we can’t reach (x, y) from origin in exactly Z steps.
- If the number of steps is not less than |x|+|y| then, we have to check below two conditions to check if we can reach to (x, y) or not:
- If Z ≥ |x| + |y|, and
- If (Z – |x| + |y|)%2 is 0.
- For the second conditions in the above step, if we reach (x, y), we can take two more steps such as (x, y)–>(x, y+1)–>(x, y) to come back to the same position (x, y). And this is possible only if different between them is even.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: 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.
- Check if it is possible to move from (0, 0) to (X, Y) in exactly K steps
- Number of ways to reach (M, N) in a matrix starting from the origin without visiting (X, Y)
- Number of ways to reach (X, Y) in a matrix starting from the origin
- Check if a destination is reachable from source with two movements allowed | Set 2
- Reaching a point using clockwise or anticlockwise movements
- Find the maximum possible distance from origin using given points
- Number of steps required to reach point (x,y) from (0,0) using zig-zag way
- Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3
- Program to check Plus Perfect Number
- Find the minimum number of steps to reach M from N
- Minimize the number of steps required to reach the end of the array | Set 2
- 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
- Minimize steps defined by a string required to reach the destination from a given source
- Maximum index a pointer can reach in N steps by avoiding a given index B
- Total position where king can reach on a chessboard in exactly M moves
- Total position where king can reach on a chessboard in exactly M moves | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.