#K76192. Border Students Extraction

    ID: 34588 Type: Default 1000ms 256MiB

Border Students Extraction

Border Students Extraction

You are given a matrix (grid) of integers representing the student numbers seated in a classroom. The students are arranged in N rows and M columns. Your task is to extract the numbers of the students lying along the border of the grid, traversed in a clockwise order.

The order of extraction is as follows:

  • Start with the top row (all the elements from left to right).
  • Traverse down the rightmost column (excluding the already processed top-right element).
  • If there is more than one row, traverse the bottom row in reverse order (from right to left), excluding the bottom-right element if already taken.
  • If there is more than one column, traverse up the leftmost column (from bottom to top), excluding the top and bottom elements already considered.

This problem will test your implementation skills in handling two-dimensional arrays and iterating over matrix boundaries.

Note: If the grid has only one row or one column, adjust the extraction accordingly to avoid duplicates.

The formula for the extraction order can be summarized in LaTeX as follows:

\[ \text{Border} = \begin{cases} \text{top row} \cup \{a_{i,M} : 2 \leq i \leq N\} \cup \{a_{N,j} : 1 \leq j \leq M-1\text{ in reverse}\} \cup \{a_{i,1} : 2 \leq i \leq N-1 \text{ in reverse}\} & \text{if } N,M > 1\\ \text{Special handling for } N=1 \text{ or } M=1. \end{cases} \]

inputFormat

The first line of input contains two space-separated integers N and M, representing the number of rows and columns, respectively. Following are N lines, each containing M space-separated integers representing the student numbers in that row.

outputFormat

Output a single line containing the border elements extracted in clockwise order, separated by a single space.

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