Medium Matrices

Matrix Spiral

Receives an N×M matrix of integers and returns all of its elements in clockwise spiral order, starting from the top-left corner. It keeps four boundary pointers — top, bottom, left and right — and on each lap walks the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top, shrinking the matching boundary inward after each side. It repeats until the boundaries cross, so every cell is visited exactly once. Returns a new array with the values in spiral order; an empty matrix yields an empty array, a single row is returned left to right, and a single column top to bottom.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References