Problem
On a 0-indexed 8 x 8
chessboard, there can be multiple black queens and one white king.
You are given a 2D integer array queens
where queens[i] = [xQueeni, yQueeni]
represents the position of the ith
black queen on the chessboard.
You are also given an integer array king
of length 2
where king = [xKing, yKing]
represents the position of the white king.
Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= queens.length < 64
queens[i].length == king.length == 2
0 <= xQueeni, yQueeni, xKing, yKing < 8
- All the given positions are unique.
Solution
Method 1 – Directional Search
Intuition
For each of the 8 directions a queen can attack, move step by step from the king’s position and stop at the first queen encountered. This ensures only the closest queen in each direction is considered.
Approach
- Store all queen positions in a set for O(1) lookup.
- For each of the 8 directions, move from the king’s position until out of bounds or a queen is found.
- If a queen is found, add its position to the result and stop searching in that direction.
- Return all found positions.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(Q)
, where Q is the number of queens. Each direction checks at most 8 cells, and there are 8 directions. - 🧺 Space complexity:
O(Q)
, for storing the queen positions in a set.