Leetcode 1222: Queens That Can Attack the King

grid47
grid47
Exploring patterns and algorithms
Jul 7, 2024 6 min read

On an 8x8 chessboard, there are multiple black queens and one white king. You are given the positions of the black queens and the white king. Your task is to find all the black queens that can directly attack the white king. A queen can attack the king if they share the same row, column, or diagonal.
Problem
Approach
Steps
Complexity
Input: You are given two inputs: a 2D array 'queens' where each element represents the position of a black queen, and a 1D array 'king' representing the position of the white king.
Example: queens = [[2, 3], [1, 1], [5, 2], [0, 7], [4, 6]], king = [2, 2]
Constraints:
• 1 <= queens.length < 64
• queens[i].length == king.length == 2
• 0 <= xQueeni, yQueeni, xKing, yKing < 8
• All the given positions are unique.
Output: Return a list of coordinates of the black queens that can attack the king.
Example: [[2, 3], [5, 2], [1, 1]]
Constraints:
• The output should include all the black queens that can attack the king, in any order.
Goal: Find all queens that can attack the white king.
Steps:
• 1. Mark the positions of all black queens on the chessboard.
• 2. Iterate over all possible directions from the king's position.
• 3. Check if there is a queen in each direction.
• 4. If a queen is found, add it to the result list and stop checking further in that direction.
Goal: You must work within the limits of the 8x8 chessboard and handle up to 63 black queens.
Steps:
• The chessboard is fixed in size at 8x8.
• There can be up to 63 queens on the board.
Assumptions:
• Each position is unique, meaning no two queens or the king can occupy the same square.
Input: Input: queens = [[2, 3], [1, 1], [5, 2], [0, 7], [4, 6]], king = [2, 2]
Explanation: The queens at positions (2, 3), (5, 2), and (1, 1) are in the same row, column, or diagonal as the king. Thus, they can directly attack the king.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus