P2239 [NOIP 2014 Junior] Spiral Matrix

Background

NOIP 2014 Junior T3.

Description

A spiral matrix with $n$ rows and $n$ columns can be generated as follows: Starting from the top-left corner (row $1$, column $1$), initially move to the right. If the cell ahead has not been visited, keep moving forward; otherwise, turn right. Repeat this process until all cells in the matrix have been visited. According to the visiting order, fill the cells with $1, 2, 3, \dots, n^2$ in sequence to form a spiral matrix. Below is the spiral matrix when $n = 4$. $$\begin{pmatrix} 1 & 2 & 3 & 4 \\ 12 & 13 & 14 & 5 \\ 11 & 16 & 15 & 6 \\ 10 & 9 & 8 & 7 \\ \end{pmatrix}$$ Given the matrix size $n$ and $i$ and $j$, please compute the number at row $i$, column $j$ in this matrix.

Input Format

A single line containing three integers $n$, $i$, $j$, separated by a single space. They represent the matrix size, and the row and column of the number to query.

Output Format

A single integer, the number at row $i$, column $j$ in the corresponding matrix.

Explanation/Hint

Constraints - For $50\%$ of the testdata, $1 \leqslant n \leqslant 100$. - For $100\%$ of the testdata, $1 \leqslant n \leqslant 30{,}000$; $1 \leqslant i \leqslant n$; $1 \leqslant j \leqslant n$. Translated by ChatGPT 5