Skip to main content
Back to problems
Codeforces
Easy
Arrays
Matrices
Simulation
Little Elephant and Magic Square

Determine whether a small square grid is an odd-sized magic square: all rows, columns, and diagonals have the same sum.

Acceptance 0%
Problem Statement

Problem

You are given an n×nn \times n square grid of integers. Your task is to determine whether the grid is a magic square.

A square grid is considered a magic square if:

  • the sums of all rows are equal,
  • the sums of all columns are equal,
  • the sums of the two main diagonals are equal,
  • and all of these sums are the same value.

For this problem, the grid is small enough that direct checking of all required sums is sufficient.

Goal

Return whether the provided square grid satisfies the magic square condition.

Input Format

  • The first line contains an integer nn.
  • The next nn lines contain nn integers each, describing the grid.

Output Format

  • Print YES if the grid is a magic square.
  • Otherwise, print NO.

Constraints

  • 1n1 \le n
  • The grid is square with nn rows and nn columns.
  • Integer values fit in standard 32-bit signed range.
  • A direct O(n2)O(n^2) check is sufficient.
Examples
Sample cases returned by the problem API.

Example 1

Input

3
8 1 6
3 5 7
4 9 2

Output

YES

Explanation

Every row, column, and both diagonals sum to 15.

Example 2

Input

3
1 2 3
4 5 6
7 8 9

Output

NO

Explanation

The row sums are all 6, 15, and 24, so the grid is not a magic square.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.