#C12648. Spiral Order Traversal of a Matrix

    ID: 42098 Type: Default 1000ms 256MiB

Spiral Order Traversal of a Matrix

Spiral Order Traversal of a Matrix

You are given a matrix of integers with (R) rows and (C) columns. Your task is to print the elements of the matrix in spiral order. The spiral starts at the top left corner and proceeds to the right, then down, then left, and then up, continuing inward until all elements have been printed. This is a classical problem that tests your ability to manipulate and traverse multi-dimensional arrays.

inputFormat

The input is given from standard input (stdin) and is formatted as follows:

  • The first line contains two space-separated integers \(R\) and \(C\), representing the number of rows and columns of the matrix.
  • The next \(R\) lines each contain \(C\) space-separated integers representing the elements of the matrix.
  • If \(R = 0\) or \(C = 0\), the matrix is considered empty.

outputFormat

Output the elements of the matrix in spiral order on a single line, with each element separated by a single space. The output should be written to standard output (stdout).

## sample
3 3
1 2 3
4 5 6
7 8 9
1 2 3 6 9 8 7 4 5