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.
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.
O(rc log(rc)) time and O(rc) output space.
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
}
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[0] - rCenter) + abs(cell[1] - cCenter))
function allCellsDistOrder(rows: number, cols: number, rCenter: number, cCenter: number): number[][] {
const cells: number[][] = []; for (let row = 0; row < rows; row += 1) for (let column = 0; column < cols; column += 1) cells.push([row, column]);
return cells.sort((left, right) => Math.abs(left[0] - rCenter) + Math.abs(left[1] - cCenter) - Math.abs(right[0] - rCenter) - Math.abs(right[1] - cCenter));
}