[
2d-array
simulation
]
Leetcode 1222. Queens That Can Attack the King
Problem statement
https://leetcode.com/problems/queens-that-can-attack-the-king/
Solution
Just do what is asked in this problem: simulate the process.
Complexity
It is O(T^2)
for time and space, where T = 8
is the size of board.
Code
class Solution:
def queensAttacktheKing(self, queens, king):
set_queens = set((x, y) for x, y in queens)
x, y = king
ans = []
for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1):
for steps in range(1, 8):
x2, y2 = x + dx*steps, y + dy*steps
if not 0 <= x2 < 8 or not 0 <= y2 < 8: break
if (x2, y2) in set_queens:
ans += [(x2, y2)]
break
return ans