問題一覧 > 通常問題

No.217 Let's Make a Magic Square

レベル : / AI推定難易度 : 1425 / 実行時間制限 : 1ケース 5.000秒 / メモリ制限 : 512 MB / スペシャルジャッジ問題 (複数の解が存在する可能性があります)
タグ : (AC するまで非表示) / 解いたユーザー数 83
作問者 : 👑 tails
お気に入りにしたユーザー ProblemId : 557 / 自分の提出
問題文最終更新日: 2026-06-26 09:13:28
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 106 (順位表) の他の問題:

Problem Statement

Construct 1 magic square with $N$ rows and $N$ columns.
In general, there are multiple magic squares with $N$ rows and $N$ columns, but any of them is acceptable.

In this problem, a magic square with $N$ rows and $N$ columns is
an arrangement of the integers from $1$ to $N^2$ in $N$ rows and $N$ columns
such that the sums of the numbers in each row, in each column, and on each of the 2 diagonals are all equal.

An example of a magic square with $3$ rows and $3$ columns:

2 9 4
7 5 3
6 1 8

Since this algorithm rarely appears in competitive programming, you may refer to the section "How to construct magic squares" of Wikipedia "Magic square" as a hint.
To find the answer, you need to combine several algorithms.

Input

$N$

$3 \le N \le 20$
$N$ is an integer.

Output

$A_{1,1}$ $A_{1,2}$ $\dots$ $A_{1,N}$
$A_{2,1}$ $A_{2,2}$ $\dots$ $A_{2,N}$
$\vdots$
$A_{N,1}$ $A_{N,2}$ $\dots$ $A_{N,N}$

Output 1 magic square with $N$ rows and $N$ columns.
On the $y$-th line of the output, print the numbers in the $y$-th row of the magic square, separated by spaces, in order starting from the number in column $1$, $A_{y,1}$.
(Extra spaces before or after the numbers are allowed.)

Sample

Sample 1
Input
3
Output
2 9 4
7 5 3
6 1 8

The above output is an example.
There are multiple magic squares with $3$ rows and $3$ columns, and you may output any of them.

提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。