Sort Concentric Matrix Borders Clockwise
Learn this problemProblem statement
Given a rectangular integer matrix, divide it into concentric borders by repeatedly removing the current outer border.
For each border independently, collect its values in clockwise order starting at that border's top-left cell, sort the collected values in ascending order, and write them back along the same traversal.
Traverse a nondegenerate border across the top edge from left to right, down the right edge, across the bottom edge from right to left, and up the left edge. Visit every cell exactly once. Traverse a one-row border from left to right and a one-column border from top to bottom.
Return the resulting matrix.
Function
sortMatrixBorders(matrix: int[][]) → int[][]Examples
Example 1
matrix = [[9, 7, -4, 5], [1, 6, 2, -6], [12, 20, 2, 0]]return = [[-6, -4, 0, 1], [20, 2, 6, 2], [12, 9, 7, 5]]The outer border is sorted and rewritten clockwise as [-6, -4, 0, 1, 2, 5, 7, 9, 12, 20]. The inner one-row border [6, 2] becomes [2, 6].
Example 2
matrix = [[3], [1], [2]]return = [[1], [2], [3]]The only border is one column, so it is visited from top to bottom and sorted in that order.
Constraints
1 <= matrix.length <= 2001 <= matrix[i].length <= 200- Every row has the same length.
-10^9 <= matrix[i][j] <= 10^9