#1222
Medium Algorithms Queens that can attack the king
Array Matrix Simulation
72.6% acceptance
Feb 25, 2026
1004
154
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn queens_attackthe_king(queens: Vec<Vec<i32>>, king: Vec<i32>) -> Vec<Vec<i32>> {
use std::collections::HashSet;
let queen_set: HashSet<(i32, i32)> = queens.iter().map(|q| (q[0], q[1])).collect();
let mut result = vec![];
let kx = king[0];
let ky = king[1];
let dirs: [(i32, i32); 8] = [(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)];
for (dx, dy) in dirs {
let mut x = kx + dx;
let mut y = ky + dy;
while x >= 0 && x < 8 && y >= 0 && y < 8 {
if queen_set.contains(&(x, y)) {
result.push(vec![x, y]);
break;
}
x += dx;
y += dy;
}
}
result
}
}