 All Problems
Spiral Matrix
medium
arrays
matrix
microsoft
amazon
apple
google

Given an m × n matrix, return all elements in spiral order.

Example 1:

Input:
3 3
1 2 3
4 5 6
7 8 9
Output: 1 2 3 6 9 8 7 4 5

Example 2:

Input:
3 4
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

Constraints:

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 10

Input format: First line: m n. Then m rows of n space-separated integers.

Output format: Space-separated spiral order.

Run to check your code against the sample cases, or submit to run every case