Matrix Cells in Distance Order Problem
Description
LeetCode Problem 1030.
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r_1, c_1) and (r_2, c_2) is |r_1 - r_2| + |c_1 - c_2|.
Example 1:
Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (0, 0) to other cells are: [0,1]
Example 2:
Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1
Output: [[0,1],[0,0],[1,1],[1,0]]
Explanation: The distances from (0, 1) to other cells are: [0,1,1,2]
The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.
Example 3:
Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2
Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]
There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
Constraints:
1 <= rows, cols <= 1000 <= rCenter < rows0 <= cCenter < cols
Solution
Approach: BFS From the Center
The Manhattan distance between two cells is exactly the number of steps up, down, left or right needed to go from one to the other, and inside a full rectangle there is always such a shortest path. So a breadth-first search that starts at (rCenter, cCenter) reaches the cells in order of their distance: first the center, then all cells at distance 1, then distance 2, and so on.
Start the queue with the center and mark it visited. Repeatedly take the next cell from the queue, append it to the answer, and push its unvisited neighbors inside the matrix, marking them as visited when they are pushed so no cell is added twice. The order in which cells leave the queue is the answer.
Cells at the same distance may come out in any order, which the problem allows. A simpler alternative is to list all cells and sort them by distance, at the cost of O(R * C log(R * C)) time.
Complexity: O(R * C) time and space, where R and C are the numbers of rows and columns.
from collections import deque
class Solution:
def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
# BFS from the center visits the cells in order of their distance.
seen = [[False] * cols for _ in range(rows)]
seen[rCenter][cCenter] = True
queue = deque([(rCenter, cCenter)])
order = []
while queue:
r, c = queue.popleft()
order.append([r, c])
for x, y in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= x < rows and 0 <= y < cols and not seen[x][y]:
seen[x][y] = True
queue.append((x, y))
return order