Skills101
← All coding problems

Boundary Traversal of a Matrix

easyMatrix+10 XPTime limit 2s

Print the elements on the border of the matrix in clockwise order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row and up the left column. Print every border cell exactly once.

Input:

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

Output: the border values on one line.

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

Watch out: a single row or a single column has no "other side" — don't print its cells twice. Corners belong to only one of the four sides.

Sample input 1

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

Sample output 1

1 2 3 4 8 12 11 10 9 5

Sample input 2

1 3
1 2 3

Sample output 2

1 2 3

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.