题目如下:
解题思路:往king的上下左右,上左,上右,下左,下右八个方向移动,如果某个方向遇到queen,则表示这个queen能攻击到king,然后停止这个方向的移动。
代码如下:
class Solution(object):
def queensAttacktheKing(self, queens, king):
"""
:type queens: List[List[int]]
:type king: List[int]
:rtype: List[List[int]]
"""
res = []
dic = {}
for (x,y) in queens:dic[(x,y)] = 1
direction = [(0,1),(0,-1),(-1,0),(1,0),(-1,-1),(-1,1),(1,-1),(1,1)]
for (x,y) in direction:
kx,ky = king
while kx + x >= 0 and kx + x < 8 and ky+y>=0 and ky+ y < 8:
if (kx+x,ky+y) in dic:
res.append([kx+x,ky+y])
break
kx += x
ky += y
return res