#1030
Easy Algorithms Matrix cells in distance order
Array Math Geometry Sorting Matrix
73.9% acceptance
Feb 25, 2026
814
345
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 (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn all_cells_dist_order(rows: i32, cols: i32, r_center: i32, c_center: i32) -> Vec<Vec<i32>> {
let mut cells: Vec<Vec<i32>> = (0..rows).flat_map(|r| (0..cols).map(move |c| vec![r,c])).collect();
cells.sort_by_key(|c| (c[0]-r_center).abs() + (c[1]-c_center).abs());
cells
}
}