leetcode-158周赛-5223-可以攻击国王的皇后

题目描述:

 

 自己的提交:

class Solution:
    def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
        if not queens:return []
        res = []
        row,col = 8,8
        def helper(i,j,queens):
            if 0<=i<row and 0<j<col and [i,j] in queens:
                return True
            return False
        opt = [[0,1],[1,0],[-1,0],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]
        for x,y in opt:
            i = king[0] + x
            j = king[1] + y
            while 0<=i<row and 0<=j<col:
                if [i,j] in queens:
                    res.append([i,j])
                    break
                else:
                    i += x
                    j += y
                    
        return res
                
            

优化:

class Solution(object):
    def queensAttacktheKing(self, queens, king):
        ans = []
        q = set([tuple(x) for x in queens])
        for i in [-1,0,1]:
            for j in [-1,0,1]:
                if i!=0 or j!=0:
                    x,y=king
                    while 0<=x<=7 and 0<=y<=7:
                        if (x,y) in q:
                            ans.append([x,y])
                            break
                        x+=i
                        y+=j
        return ans

猜你喜欢

转载自www.cnblogs.com/oldby/p/11669530.html