Queens That Can Attack the King Problem
Description
LeetCode Problem 1222.
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] = [xQueen_i, yQueen_i] represents the position of the i^th 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:

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 and the three queens that cannot attack the king (i.e., marked with red dashes).
Example 2:

Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
Output: [[2,2],[3,4],[4,4]]
Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Constraints:
1 <= queens.length < 64queens[i].length == king.length == 20 <= xQueen_i, yQueen_i, xKing, yKing < 8- All the given positions are unique.
Solution
Approach: Walk Out from the King
A queen attacks along its row, column and both diagonals, but another piece in between blocks it. So instead of checking each queen, look from the king's side: in each of the 8 directions, walk away from the king one square at a time, and the first queen met (if any) is the only one in that direction that can attack.
Mark the queens on an 8 x 8 board first, so each step is a single lookup. For each direction (dx, dy) with dx, dy in {-1, 0, 1}, not both 0, step from the king until leaving the board; at the first marked square, record it and stop that direction.
The tricky part is the blocking: a queen behind another queen in the same direction is not an answer, and stopping at the first one handles it.
Complexity: O(q + 8 · 8) time and O(8 · 8) extra space, where q is the number of queens: the board is filled once and each of the 8 rays has at most 7 squares.
class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
occupied = {(x, y) for x, y in queens}
ans = []
# Walk out from the king in each of the 8 directions; only the first queen on a ray can attack.
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue
x, y = king[0] + dx, king[1] + dy
while 0 <= x < 8 and 0 <= y < 8:
if (x, y) in occupied:
ans.append([x, y])
break
x, y = x + dx, y + dy
return ans