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

In chess, a queen is the most powerful piece that can move horizontally, vertically, and diagonally any number of squares. Given two coordinates on a chessboard representing a queen's position and a target cell, we need to determine if the queen can attack that position.

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

Q O Queen Attack Example (1,1) (4,4)

Algorithm

To solve this, we check three conditions ?

  • If x-coordinate of Queen is same as x-coordinate of Opponent (same column)
  • If y-coordinate of Queen is same as y-coordinate of Opponent (same row)
  • If |x of Q - x of O| equals |y of Q - y of O| (diagonal attack)

Implementation

def solve(Q, O):
    # Check if queen and opponent are in same column
    if Q[0] == O[0]:
        return True
    
    # Check if queen and opponent are in same row
    if Q[1] == O[1]:
        return True
    
    # Check if queen can attack diagonally
    if abs(Q[0] - O[0]) == abs(Q[1] - O[1]):
        return True
    
    return False

# Test the function
Q = (1, 1)
O = (4, 4)
print(f"Queen at {Q} can attack opponent at {O}: {solve(Q, O)}")
Queen at (1, 1) can attack opponent at (4, 4): True

Multiple Test Cases

Let's test different scenarios to understand how the queen attacks ?

def solve(Q, O):
    if Q[0] == O[0]:  # Same column
        return True
    if Q[1] == O[1]:  # Same row
        return True
    if abs(Q[0] - O[0]) == abs(Q[1] - O[1]):  # Diagonal
        return True
    return False

# Test cases
test_cases = [
    ((2, 3), (2, 7)),  # Same column
    ((4, 2), (1, 2)),  # Same row  
    ((3, 3), (6, 6)),  # Diagonal
    ((1, 1), (3, 4))   # No attack possible
]

for queen, opponent in test_cases:
    result = solve(queen, opponent)
    print(f"Queen {queen} ? Opponent {opponent}: {result}")
Queen (2, 3) ? Opponent (2, 7): True
Queen (4, 2) ? Opponent (1, 2): True
Queen (3, 3) ? Opponent (6, 6): True
Queen (1, 1) ? Opponent (3, 4): False

How It Works

The diagonal check uses the mathematical property that two points lie on the same diagonal if the absolute difference in their x-coordinates equals the absolute difference in their y-coordinates. This works for both main diagonal (top-left to bottom-right) and anti-diagonal (top-right to bottom-left) directions.

Conclusion

A queen can attack any position on the same row, column, or diagonal. The solution checks these three conditions using coordinate comparisons and absolute differences for diagonal validation.

Updated on: 2026-03-25T14:07:25+05:30

814 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements