每日一题 1222. 可以攻击国王的皇后

难度:中等
每日一题 1222. 可以攻击国王的皇后_第1张图片
很简单,和昨天一样,以国王为中心,模拟8个方向上是否有皇后及第一个遇到的皇后的坐标

class Solution:
    def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
        ans = []
        board = [[0 for col in range(8)] for row in range(8)]
        for q in queens:
            board[q[0]][q[1]] = 1
        
        for i, j in [(-1, 0), (1, 0), (-1, -1), (-1, 1), (0, 1), (0, -1), (1, 1), (1, -1)]:
            nx, ny = king[0], king[1]
            while nx >= 0 and nx < 8 and ny >= 0 and ny < 8:
                if board[nx][ny] == 1:
                    ans.append([nx, ny])
                    break
                nx += i
                ny += j

        return ans

你可能感兴趣的:(用Python刷力扣,python,算法,leetcode)