#K83882. Magic Square Completion Checker

    ID: 36296 Type: Default 1000ms 256MiB

Magic Square Completion Checker

Magic Square Completion Checker

You are given an n x n matrix where some values may be undefined (represented as -1). Your task is to determine whether it is possible to complete the matrix to form a magic square. In a magic square, every row, every column, and both main diagonals all sum to the same value.

The matrix has the following properties:

  • n is an integer satisfying \(2 \le n \le 100\).
  • Cells with a value of -1 indicate that the value is currently undefined.
  • For n = 2, the answer is always "NO".

To decide if it is possible to complete the matrix into a magic square, one should:

  1. Find at least one complete row, column, or diagonal (i.e. with no -1 entries) and take its sum as the candidate magic sum \(M\).
  2. Verify that all completely defined rows, columns, and diagonals have the same sum \(M\). If not, output "NO".
  3. For any partially defined row, column, or diagonal, ensure that the sum of its known entries does not exceed \(M\). If any such sum is greater than \(M\), output "NO".

If all these conditions are met, output "YES"; otherwise, output "NO".

Note: Input is read from standard input and output is written to standard output.

inputFormat

The first line of input contains an integer n denoting the size of the matrix.

The next n lines each contain n space-separated integers. Each integer represents an element of the matrix. A value of -1 indicates an undefined entry.

outputFormat

Output a single line containing either "YES" if it is possible to complete the matrix as a magic square based on the rules described, or "NO" otherwise.

## sample
3
8 1 6
3 5 7
-1 -1 -1
YES