09 Sept 2026Go / Python / TypeScriptEasy

Matrix Cells in Distance Order

Return all matrix coordinates ordered by Manhattan distance from a chosen cell.

Enumerate every coordinate and sort by the sum of its row and column distance from the center.

complexity

O(rc log(rc)) time and O(rc) output space.

solution files

  • Go matrix-cells-in-distance-order/solution.go
  • Python matrix-cells-in-distance-order/solution.py
  • TypeScript matrix-cells-in-distance-order/solution.ts

Solution files

Gomatrix-cells-in-distance-order/solution.go
package main

import "sort"

func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int {
	cells := make([][]int, 0, rows*cols)
	for row := 0; row < rows; row++ {
		for column := 0; column < cols; column++ {
			cells = append(cells, []int{row, column})
		}
	}
	distance := func(cell []int) int {
		row := cell[0] - rCenter
		if row < 0 {
			row = -row
		}
		column := cell[1] - cCenter
		if column < 0 {
			column = -column
		}
		return row + column
	}
	sort.Slice(cells, func(i int, j int) bool { return distance(cells[i]) < distance(cells[j]) })
	return cells
}
Pythonmatrix-cells-in-distance-order/solution.py
class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> list[list[int]]:
        cells = [[row, column] for row in range(rows) for column in range(cols)]
        return sorted(cells, key=lambda cell: abs(cell[class="syntax-number">0] - rCenter) + abs(cell[class="syntax-number">1] - cCenter))
TypeScriptmatrix-cells-in-distance-order/solution.ts
function allCellsDistOrder(rows: number, cols: number, rCenter: number, cCenter: number): number[][] {
  const cells: number[][] = []; for (let row = class="syntax-number">0; row < rows; row += class="syntax-number">1) for (let column = class="syntax-number">0; column < cols; column += class="syntax-number">1) cells.push([row, column]);
  return cells.sort((left, right) => Math.abs(left[class="syntax-number">0] - rCenter) + Math.abs(left[class="syntax-number">1] - cCenter) - Math.abs(right[class="syntax-number">0] - rCenter) - Math.abs(right[class="syntax-number">1] - cCenter));
}