[Solution] Difference Matrix Solution Codechef

Difference Matrix Solution Codechef

You are given an integer . You need to find an �×� matrix such that:

  • Each element of the matrix is an integer from 1 to �2;
  • All elements of the matrix are unique;
  • The absolute difference between elements in neighbouring cells is strictly greater than 1.

It can be shown that there is at least one matrix that satisfies the given conditions. If multiple matrices satisfy the given conditions, print any.

Note that two cells are considered to be neighbours if they have a common side or a common vertex (i.e. a cell can have at most 8 neighbouring cells).

Input Format Difference Matrix Solution Codechef

  • The first line of input will contain a single integer , denoting the number of test cases.
  • Each test case contains a single line of input, an integer , denoting the number of rows and columns in the required matrix.

Output Format Difference Matrix Solution Codechef

For each test case, output  lines, where the ��ℎ line contains  space-separated integers, denoting the elements of the ��ℎ row.

Constraints Difference Matrix Solution Codechef

  • 1≤�≤1000
  • 4≤�≤1000
  • The sum of �2 over all test cases won’t exceed 106.

Sample 1: Difference Matrix Solution Codechef

Input

Output

1
4
12  10  6   14
3   8   4   1
5   15  11  9
2   7   13  16

Explanation: Difference Matrix Solution Codechef

Test case 1: The given matrix satisfies all the conditions.

91d04e4e-6629-4f0d-a880-044ece9ca436.png

Note that all elements are unique and in the range [1,�2]. Also, the absolute difference between any two neighbouring cells is greater than 1.

Leave a Comment