Check if it is possible to move from X to Z using point Y
Last Updated : 24 Apr, 2023
Given three points X, Y, and Z of a 2D plane, the task is to check if it is possible to move from X to Z using point Y with at most one turn of 90 degrees. If possible return "YES" else return "NO".
Note: Diagonal moves are not allowed, only vertical or horizontal moves are allowed.
Examples:
Input: X = {1, 3}, Y{4, 3}, Z = {4, 5} Output: YES Explanation:
Input: X = {1, 1}, Y = {2, 2}, Z = {3, 3} Output: NO Explanation: It can be verified that we can't reach point Z from X using point Y.
Brute Force Approach :
We can check all possible paths from X to Z that involve at most one turn of 90 degrees at Y. We can start by moving from X to Y in a straight line, and then from Y to Z in a straight line, and check if this path is valid. If not, we can check all paths that involve one turn of 90 degrees at Y by considering all possible directions of the turn (left, right, up, or down), and checking if each path is valid. If we find a valid path, we can return "YES", otherwise we return "NO".
Below is the Implementation of the above approach :
Output :
YES
Complexity Analysis :
The time complexity of this solution is O(1) for the initial check if X and Z are on the same line, and O(9) for the nested loops that consider all possible paths with one turn at Y. Therefore, the overall time complexity is O(1) + O(9) = O(1).
The auxiliary space of this solution is O(1) as it only uses a constant amount of additional space to store the three points and the intermediate point after the turn.
Approach: Implement the idea below to solve the problem:
The problem is observation based and can be solved via implementing those observations. For more clarification see the Concept of approach section below.
Concept of approach:
It should be noted that Reaching from X to Z is only possible when Y is an intermediate point between X and Z. We can move in the horizontal or vertical direction, So that either the Y should be in between x coordinate of X and Z or y coordinate of X and Z also. So the conditions at which reaching is possible are: