You are given an integer ‘N’. You have to return a matrix of ‘N’ rows and ‘N’ columns formed from integers 1 to N*N, such that the sum of each row, column, and two diagonals are equal. If it’s not possible, you have to return an empty array.
For Example: You are given ‘N’ = 3, the matrix formed such that sum of rows, columns, and two diagonals are equal is
[[8, 3, 4],
[1, 5, 9]
[6, 7, 2]]
The first line of input contains the integer ‘T’ representing the number of test cases.
The first line of each test case contains the single integer ‘N’ representing the given integer.
Output Format:
For each test case, print ‘CORRECT’ if the returned matrix is correct, print ‘NULL’ if it’s impossible to form the matrix with the given number.
Print a separate line for each test case.
1 <= T <= 10
1 <= N <= 1000
Time Limit: 1 sec
2
2
3
NULL
CORRECT
For the first test case, N = 2, we have to make the matrix with 1 2 3 4, which is impossible with the given conditions; hence the answer is NULL.
For the second test case N = 3, one of the matrices formed such that the sum of rows, columns, and two diagonals are equal is
[[8, 3, 4]
[1, 5, 9]
[6, 7, 2]]
1
4
CORRECT
For the test case n = 4, one of the matrices formed such that the sum of rows, columns, and two diagonals are equal is
[[16, 2, 3, 13],
[5, 11, 10, 8],
[9, 7, 6, 12],
[4, 14, 15, 1]]
Try to use backtracking.
In this approach, we will try to place every available number at a current position and check if the matrix is valid. We will keep track of the number we have already placed, so we don’t place twice.
We will create two functions checkFunction(ans) to check if the ans matrix is valid. fillMatrixUilt(n, mat, nums, row, col) is the backtracking function, where n is the number given, mat is the matrix. array keeps track of the used numbers and row, col is the current row and column of the matrix.
Algorithm:
O((N^2) ^ (N^2))), where N is the given number.
For the element of the matrix, we are trying to place 1 to N^2 number, which will cost O((N^2) ^ (N^2))) time. Hence the final time complexity is O((N^2) ^ (N^2))).
O(N^2), Where N is the given number.
We are maintaining a 2-D matrix that takes O(N^2) space. The recursion stack also takes O(N^2) space. Hence the final space complexity is O(N^2).