Skills101
← All coding problems

Spiral Matrix

mediumArrays & Hashing+20 XPTime limit 2s

Print all elements of the matrix in spiral order: start at the top-left, go right along the top row, down the right column, left along the bottom row, up the left column — then repeat on the inner part.

Input:

  • line 1: r c
  • next r lines: c integers each

Output: all r·c values on one line, in spiral order.

Constraints: 1 ≤ r, c ≤ 300, −10⁹ ≤ value ≤ 10⁹.

Watch out: single rows, single columns and non-square matrices — keep four boundaries (top, bottom, left, right) and check them after every side.

Sample input 1

3 3
1 2 3
4 5 6
7 8 9

Sample output 1

1 2 3 6 9 8 7 4 5

Sample input 2

3 4
1 2 3 4
5 6 7 8
9 10 11 12

Sample output 2

1 2 3 4 8 12 11 10 9 5 6 7

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.