14740 - Spiral Traversal   

Description

This problem is revised from example 6.27 of the textbook.

You are given an n x n matrix, where n is an odd integer.
Starting from the center of the matrix, traverse all elements in a counterclockwise spiral path.

The traversal must follow these rules:

  1. Direction order:
    Right → Up → Left → Down→ (repeat).

  2. Step lengths:

    • The number of steps in each direction follows the sequence 1,1,2,2,3,3,…

    • Each step length is repeated twice (for two consecutive directions).

    • The only exception is the last step length (n−1), which must be repeated three times to complete the outer boundary.

  3. Traversal stops when all n2 elements have been visited exactly once.

 

Sample Input/Output 2 can be visualized in the following figure.

 

Input

  • The first line contains an odd integer n (1≤n≤99).

  • The next n lines each contain nnn integers, representing the matrix elements in row-major order.

Output

Print the elements of the matrix in the order they are visited by the spiral traversal, one element per line.

Sample Input  Download

Sample Output  Download

Tags

11410EE 231002



Discuss