Start learning free

LESSON 296 OF 506 · MATRIX

Spiral Matrix in Swift

Practice O(m*n)

Given a matrix of integers matrix, with m rows and n columns, return an array with all of its elements in spiral order.

A matrix is an array of rows, and each row is an array of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right.

Spiral order starts at the top-left corner and goes clockwise around the outside: the top row from left to right, the right column from top to bottom, the bottom row from right to left, and the left column from bottom to top. Then it goes around the part that is left inside the same way, until every element has been visited exactly once.

 

Example 1:

Input: matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: Around the outside: the top row 1, 2, 3, down the right column to 6 and 9, back along the bottom row to 8 and 7, and up the left column to 4. Only 5 is left inside.

Example 2:

Input: matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Explanation: The outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5. What is left inside is a single row, 6 and 7, read from left to right.

Example 3:

Input: matrix = [
  [3],
  [2],
  [1]
]
Output: [3, 2, 1]
Explanation: With one column, the top row is just 3, and the right column goes down through 2 and 1. Nothing is left to read back up, so no element is visited twice.

 

Constraints:

  • matrix has m rows and every row has n values, with 1 <= m, n <= 500.
  • Every value is an integer between -1000 and 1000; values can be negative and can repeat.

Note:

Your algorithm should run in O(m * n) time: it visits every element once.

STEP 1 OF 19
    Ctrl + Enter to check

    Spiral Matrix in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free