#C5592. Spiral Matrix Sum

    ID: 49258 Type: Default 1000ms 256MiB

Spiral Matrix Sum

Spiral Matrix Sum

You are given an n × n integer matrix. Your task is to traverse the matrix in a spiral order, starting from the top-left corner and moving clockwise, and compute the sum of all its elements. Note that although the order in which you visit the elements is specific, the final sum remains the same as the sum of all elements in the matrix.

The spiral order traversal is defined as follows:

  • Traverse the top row from left to right.
  • Traverse the rightmost column from top to bottom.
  • If there are remaining rows, traverse the bottom row from right to left.
  • If there are remaining columns, traverse the leftmost column from bottom to top.

Mathematically, if we define the matrix as \(A_{ij}\) for \(1 \leq i, j \leq n\), you need to calculate:

[ S = \sum_{(i,j) \in \text{spiral order}} A_{ij} ]

Input/Output Requirements: The input is taken from stdin and the output should be printed to stdout.

inputFormat

The first line of input contains a single integer \(n\) (the number of rows and columns in the matrix). The following \(n\) lines each contain \(n\) space-separated integers representing the rows of the matrix.

outputFormat

Output a single integer representing the sum of all elements of the matrix when traversed in spiral order.

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