Magic Square
Time limit2sMemory limit1024 MB
Fill the empty cells with the unused numbers from 1 to N squared so every row, column, and both diagonals share one sum.
- Level
Medium7 of 10
- Topics
- Backtracking, Brute force, Math
- Solved
- No attempts yet
Problem
A magic square is an matrix that satisfies the following three conditions.
- Every entry is an integer between and .
- All entries are distinct.
- The row sums, the column sums, and the two diagonal sums are all equal.
The following matrix is a magic square.
The row sums are 8+3+4, 1+5+9, 6+7+2, the column sums are 8+1+6, 3+5+7, 4+9+2, and the two diagonal sums are 8+5+2 and 4+5+6. All eight sums equal 15.
You are given an matrix with some of its entries already filled in. Decide whether the empty entries can be filled so that the matrix becomes a magic square.
Input
The first line contains the size of the matrix () and the number of filled entries (), separated by a space.
Each of the next lines contains the row index (), the column index (), and the value () of one filled entry, separated by spaces. All the values are distinct.
Output
Print yes if the given matrix can be completed into a magic square, and no otherwise.