VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-rook-can-reach-the-given-destination-in-a-single-move/

⇱ Check if a Rook can reach the given destination in a single move - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a Rook can reach the given destination in a single move

Last Updated : 3 May, 2021

Given integers current_row and current_col, representing the current position of a Rook on an 8 × 8 chessboard and two more integers destination_row and destination_col which represents the position to be reached by a Rook. The task is to check if it is possible or not for a Rook to reach the given destination in a single move from its current position. If found to be true, print "POSSIBLE". Otherwise, print "NOT POSSIBLE".

Examples:

Input: current_row=8, current_col=8, destination_row=8, destination_col=4 
Output: POSSIBLE
Explanation: 
 

👁 Image
Possible

Input: current_row=3, current_col=2, destination_row=2, destination_col=4 
Output: NOT POSSIBLE 
Explanation: 
 

👁 Image
Not Possible


 


 

Approach: The given problem can be solved using the following observation:

On a chessboard, a rook can move as many squares as possible, horizontally as well as vertically, in a single move. Therefore, it can move to any position present in the same row or the column as in its initial position.

👁 Image

Therefore, the problem reduces to simply checking for the following two conditions: 
 

  • If destination_row and current_row are equal or not.
  • Otherwise, check if destination_col is equal to current_col or not.
  • If any of the above two conditions are satisfied, print "POSSIBLE". Otherwise, print "NOT POSSIBLE".

Below is the implementation of the above approach:


Output: 
POSSIBLE

 

Time complexity: O(1) 
Space complexity: O(1)

Comment
Article Tags: