Check if a Queen can attack a given cell on chessboard in Python


Suppose we have two coordinates on a chessboard for queen and opponent. These points are Q and O respectively. We have to check whether the queen can attack the opponent or not. As we know that the queen can attack in the same row, same column and diagonally.

So, if the input is like Q = (1, 1) O = (4, 4), then the output will be True as Q can go (4, 4) diagonally.

To solve this, we will follow these steps −

  • if x of Q is same as x of O, then
    • return True
  • if y of Q is same as y of O, then
    • return True
  • if |x of Q - x of O| is same as |y of Q - y of O|, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(Q, O):
   if Q[0] == O[0]:
      return True
   if Q[1] == O[1]:
      return True
   if abs(Q[0] - O[0]) == abs(Q[1] - O[1]):
      return True
   return False
Q = (1, 1)
O = (4, 4)
print(solve(Q, O))

Input

(1, 1), (4, 4)

Output

True

Updated on: 29-Dec-2020

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements