This page is still under construction.

Parts of this page are still being built. What you see may change.

Magic Square

Time limit2sMemory limit1024 MB

Summary
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 N×NN \times N matrix that satisfies the following three conditions.

  1. Every entry is an integer between 11 and N2N^2.
  2. All entries are distinct.
  3. The NN row sums, the NN column sums, and the two diagonal sums are all equal.

The following 3×33 \times 3 matrix is a magic square.

834
159
672

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 N×NN \times N 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 NN (2≤N≤52 \le N \le 5) and the number of filled entries EE (0≤E≤N20 \le E \le N^2), separated by a space.

Each of the next EE lines contains the row index RR (1≤R≤N1 \le R \le N), the column index CC (1≤C≤N1 \le C \le N), and the value VV (1≤V≤N21 \le V \le N^2) of one filled entry, separated by spaces. All the values VV are distinct.

Output

Print yes if the given matrix can be completed into a magic square, and no otherwise.

Examples1

  1. Example 1

    Input
    5 7
    1 4 24
    4 2 10
    5 5 11
    2 3 8
    3 2 9
    1 2 1
    4 3 21
    
    Expected output
    yes