Clockwise Matrix Boundary Traversal

Given a nonempty rectangular integer matrix, return only its outer boundary in clockwise order starting at the top-left cell. Walk the top row, right edge,…

Given a nonempty rectangular integer matrix, return only its outer boundary in clockwise order starting at the top-left cell. Walk the top row, right edge, bottom row in reverse, then left edge upward. Include each corner once. A single row or column is returned in natural order.

1 to 1000 rows, 1 to 500 columns, at most 250,000 cells; every row has the same positive length. Every cell is an integer from -1000 through 1000. The visualizer uses matrices of at most 6 rows and 6 columns; larger valid inputs are execution-only.

Example 1: input matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; output [1, 2, 3, 6, 9, 8, 7, 4]. Top 1, 2, 3; right 6, 9; bottom 8, 7; left 4. The center 5 is not on the boundary.

Example 2: input matrix = [[1, 2, 3], [4, 5, 6]]; output [1, 2, 3, 6, 5, 4]. Top 1, 2, 3; right 6; bottom 5, 4. No left interior cell remains.

Example 3: input matrix = [[1, 2, 3, 4]]; output [1, 2, 3, 4]. With one row, each cell is on the boundary and appears once from left to right.

Category: Arrays. Topic: arrays. Difficulty: Easy. Patterns: linear-scan.