Leetcode 1094 Solution

This article provides solution to leetcode question 1094 (matrix-cells-in-distance-order)

https://leetcode.com/problems/matrix-cells-in-distance-order

Solution

class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: q = collections.deque() q.append((r0, c0)) seen = {(r0, c0)} ans = []
while q: r, c = q.popleft() ans.append((r, c))
if r > 0 and (r - 1, c) not in seen: q.append((r - 1, c)) seen.add((r - 1, c))
if r < R - 1 and (r + 1, c) not in seen: q.append((r + 1, c)) seen.add((r + 1, c))
if c > 0 and (r, c - 1) not in seen: q.append((r, c - 1)) seen.add((r, c - 1))
if c < C - 1 and (r, c + 1) not in seen: q.append((r, c + 1)) seen.add((r, c + 1))
return ans