SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Spiral Matrix

Description: Given a matrix, return all its elements in spiral order: left to right along the top row, top to bottom along the right column, and so on.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2],[3,4]]
Output: [1,2,4,3]

Constraints:

1 <= число строк, столбцов <= 10

-100 <= matrix[i][j] <= 100

Recommended time and space complexity

O(m × n) time and O(1) extra space.


Hint 1

Keep four boundaries: top, bottom, left, right.


Hint 2

After traversing a side, move the corresponding boundary inward.


Hint 3

Check the boundaries before the bottom row and left column, otherwise elements get visited twice.

A problem about careful boundary handling in a 2D array. Teaches managing four pointers and avoiding double traversal.

Expected Input :

[[1,2,3],[4,5,6],[7,8,9]]

Expected Output

[1,2,3,6,9,8,7,4,5]