VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-queen-can-attack-a-given-cell-on-chessboard/

⇱ Check if a Queen can attack a given cell on chessboard - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a Queen can attack a given cell on chessboard

Last Updated : 21 Sep, 2022

Given the position of the queen (qX, qY) and the opponent (oX, oY) on a chessboard. The task is to determine whether the queen can attack the opponent or not. Note that the queen can attack in the same row, same column and diagonally.
Example: 
 

Input: qX = 4, qY = 5, oX = 6, oY = 7 
Output: Yes 
The queen can attack diagonally.

Input: qX = 1, qY = 1, oX = 3, oY = 2 
Output: No  


 


Approach: 
 

  • If qR = oR, it means that both the queen and the opponent are in the same row and the queen can attack the opponent.
  • Similarly, if qC = oC then also the queen can attack the opponent as they both are in the same column.
  • And for diagonals, if abs(qR - oR) = abs(qC - oC) i.e. queen can attack the opponent diagonally.

If all of the above conditions fail then the opponent is safe from the queen.

Below is the implementation of the above approach:
 


Output: 
No

 

Time complexity: O(1)
Auxiliary space: O(1)

Comment
Article Tags: