### PROBLEM LINK:

**Author:** AmirReza PoorAkhavan

**Tester:** Danial Erfanian

**Editorialist:** Michael Nematollahi

### PREREQUISITES:

NONE

### PROBLEM:

You are given a number N and you are asked to output an N \times N matrix consisting of numbers from 1 to N \times N according to a given pattern.

### EXPLANATION:

To solve this problem, let’s first find out what the pattern really is.

By looking at the given matrix, we realize that each anti-diagonal of the matrix consists of some consecutive numbers written from top to bottom. the first anti-diagonal is composed of only number 1, the second is composed of numbers 2 and 3, and the following anti-diagonals are filled similarly.

So it turns out the task is fairly simple. We have to start from the first anti-diagonal, go through all of those diagonals one by one and write the numbers from top to bottom starting from 1.

So all that’s left is to go through anti-diagonals one by one efficiently. Let’s enumerate the rows of the matrix from top to bottom starting from 0. Similarly, let’s enumerate the columns from left to right starting from 0. Now let’s enumerate the anti-diagonals starting from 0. Note that based on our enumeration, the sum of row and column indices of all the cells of the matrix that are on the i^{th} anti-diagonal is equal to i. We can write a neat implementation based on this. We simply iterate over numbers from 0 up to 2 \times (N-1) and deal with the i^{th} anti-diagonal on the i^{th} iteration.

The time complexity of this solution is O(N^2)

Refer to the editorialist’s code to see the implementation of the described solution.

### AUTHOR’S AND TESTER’S SOLUTIONS:

Author’s solution can be found here

Tester’s solution can be found here

Editorialist’s solution can be found here