VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-all-the-queens-attacking-the-king-in-a-chessboard/

⇱ Find all the queens attacking the king in a chessboard - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find all the queens attacking the king in a chessboard

Last Updated : 23 Jul, 2025

Given a 2D array queens[][] consisting of coordinates of N queens in an 8 * 8 chessboard and an array king[] denoting the coordinates of the king, the task is to find the queens that are attacking the king

Examples:

Input: queens[][] = {{0, 1}, {1, 0}, {4, 0}, {0, 4}, {3, 3}, {2, 4}}, king[] = {2, 3} 
Output: {{0, 1}, {2, 4}, {3, 3}}

Explanation:The queens at coordinates {0, 1} and {3, 3} are diagonally attacking the king and the queen at {2, 4} is vertically below the king.

Input: queens[][]] = {{4, 1}, {1, 0}, {4, 0}}, king[] = {0, 0} 
Output : {{1, 0}} 

Approach Follow the steps below to solve the problem:

  • Iterate over the array queens[][].
  • For every coordinate traversed, check for all possibilities of attacking the king, i.e. horizontally, vertically and diagonally. If found to be attacking the king, check for the following: 
    • If no other queen is attacking the king from that direction, including the current king as an attacker.
    • If an attacker is already present in that direction, check if the current queen is the closest attacker or not. If found to be true, including the cent queen as an attacker. Otherwise, proceed to the next coordinates.
  • Finally, print all the coordinates.

Below is the implementation of the above approach:


Output: 
0 1 
2 4 
3 3

 

Time Complexity: O(N), where N is the number of queens 
Auxiliary Space: O(N)

Comment