Queens That Can Attack the King

LeetCode

LeetCode: https://leetcode.com/problems/queens-that-can-attack-the-king/

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.

Example 1:

Queens Attack Example

  • Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
  • Output: [[0,1],[1,0],[3,3]]
  • Explanation: The diagram above shows the three queens that can directly attack the king.
1def queensAttacktheKing(queens: List[List[int]], king: List[int]) -> List[List[int]]:
2 result = []
3 queens_set = {(r, c) for r, c in queens}
4 # 8 directions: up, down, left, right, diagonals
5 directions = [
6 (-1, -1), (-1, 0), (-1, 1),
7 (0, -1), (0, 1),
8 (1, -1), (1, 0), (1, 1)
9 ]
10
11 for dr, dc in directions:
12 r, c = king
13 # Move in the current direction until we find a queen or hit the edge
14 while True:
15 r += dr
16 c += dc
17 if not (0 <= r < 8 and 0 <= c < 8):
18 break # Out of bounds
19 if (r, c) in queens_set:
20 result.append([r, c])
21 break # Found the first queen in this direction
22
23 return result
K
Q
0
0
Q
0
0
0
Q
0
0
0
0
0
0
0
0
0
0
0
Q
0
0
0
0
0
0
Q
0
0
0
0
Q
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
king=[0, 0]
result=[]
Step 1 / 5
Step 1:
Initialize the 8x8 board. King is at [0,0]. Queens are placed at various positions.
Focus: select @ [0]