JZX轻语:简

LeetCode 1222 - 可以攻击国王的皇后

发表于2024年07月09日

#模拟

类似于1958-检查操作是否合法,枚举八个方向,如果有一个方向具有皇后,则将该皇后坐标添加到结果数组中(后续该方向不用寻找了,只关注该方向的第一个皇后),然后转向下一个方向继续寻找。

class Solution:
    moves = (
        (-1, 0),  # 左
        (1, 0),  # 右
        (0, -1),  # 上
        (0, 1),  # 下
        (-1, -1),  # 左上
        (1, 1),  # 右下
        (1, -1),  # 左下
        (-1, 1)  # 右上
    )

    def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
        has_queen = [[False] * 8 for _ in range(8)]
        for r, c in queens:
            has_queen[r][c] = True
        ans = []
        for move in self.moves:
            r, c = king
            while 0 <= r < 8 and 0 <= c < 8:
                if has_queen[r][c]:
                    ans.append([r, c])
                    break
                r, c = r + move[0], c + move[1]
        return ans

闪念标签:LC

题目链接:https://leetcode.cn/problems/queens-that-can-attack-the-king/