|
| 1 | +/** |
| 2 | + * 1222. Queens That Can Attack the King |
| 3 | + * https://leetcode.com/problems/queens-that-can-attack-the-king/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king. |
| 7 | + * |
| 8 | + * You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the |
| 9 | + * position of the ith black queen on the chessboard. You are also given an integer array king |
| 10 | + * of length 2 where king = [xKing, yKing] represents the position of the white king. |
| 11 | + * |
| 12 | + * Return the coordinates of the black queens that can directly attack the king. You may return |
| 13 | + * the answer in any order. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} queens |
| 18 | + * @param {number[]} king |
| 19 | + * @return {number[][]} |
| 20 | + */ |
| 21 | +var queensAttacktheKing = function(queens, king) { |
| 22 | + const [kingX, kingY] = king; |
| 23 | + const queenSet = new Set(queens.map(([x, y]) => `${x},${y}`)); |
| 24 | + const attackers = []; |
| 25 | + const directions = [ |
| 26 | + [-1, 0], [1, 0], [0, -1], [0, 1], |
| 27 | + [-1, -1], [-1, 1], [1, -1], [1, 1] |
| 28 | + ]; |
| 29 | + |
| 30 | + for (const [dx, dy] of directions) { |
| 31 | + let x = kingX + dx; |
| 32 | + let y = kingY + dy; |
| 33 | + |
| 34 | + while (x >= 0 && x < 8 && y >= 0 && y < 8) { |
| 35 | + const pos = `${x},${y}`; |
| 36 | + if (queenSet.has(pos)) { |
| 37 | + attackers.push([x, y]); |
| 38 | + break; |
| 39 | + } |
| 40 | + x += dx; |
| 41 | + y += dy; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return attackers; |
| 46 | +}; |
0 commit comments