Leetcode 1222. Queens That Can Attack the King
📅2023-09-14🧐114
https://leetcode.com/problems/queens-that-can-attack-the-king/
Actually we don't need to do DFS or BFS, just a simple linear search would be fine.
class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
# define directions
dirs = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
# set has faster search performance than list
qs = {(q[0], q[1]) for q in queens}
ans = []
# traverse all directions
for r, c in dirs:
# initial point of current direction
nr, nc = king[0] + r, king[1] + c
# if the point still on the board, we start to move further on this direction
while nr >= 0 and nc >= 0 and nr <= 7 and nc <= 7:
# if we find answer on this direction, exit
if (nr, nc) in qs:
ans.append([nr, nc])
break
# move to next point on this direction
nr += r
nc += c
return ans