Given a number N, place numbers from the range [1, N2] in an NxN matrix such that sum in every row is equal.
Input: N = 3 Output: 1 5 9 2 6 7 3 4 8 Sum in 1st row: 15 Sum in 2nd row: 15 Sum in 2nd row: 15 Input: N = 5 Output: 1 7 13 19 25 2 8 14 20 21 3 9 15 16 22 4 10 11 17 23 5 6 12 18 24
A Greedy Approach has been used to fill the matrix, where the insertion of elements in the matrix is done row-wise. The required matrix can be obtained using below steps:
- Fill the matrix initially with numbers in the range [1, N2] using matrix traversal.
- Traverse the matrix and change every position in a new matrix considering it as answer matrix by answer[i][j] = mat[j][(i+j)%n].
Below is the implementation of the above approach:
1 7 13 19 25 2 8 14 20 21 3 9 15 16 22 4 10 11 17 23 5 6 12 18 24
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if it is possible to create a matrix such that every row has A 1s and every column has B 1s
- Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
- Find a Square Matrix such that sum of elements in every row and column is K
- Print an N x M matrix such that each row and column has all the vowels in it
- Construct a matrix such that union of ith row and ith column contains every element from 1 to 2N-1
- Check if a number from every row can be selected such that xor of the numbers is greater than zero
- Find an N x N grid whose xor of every row and column is equal
- Replace every matrix element with maximum of GCD of row or column
- Count of elements of an array present in every row of NxM matrix
- Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
- Sum of matrix in which each element is absolute difference of its row and column numbers
- Count positions in Binary Matrix having equal count of set bits in corresponding row and column
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Check if a given matrix can be converted to another given matrix by row and column exchanges
- Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix
- Print all possible paths from the first row to the last row in a 2D array
- Given a Boolean Matrix, find k such that all elements in k'th row are 0 and k'th column are 1.
- Find the row whose product has maximum count of prime factors
- In-place convert matrix in specific order
- Count of N digit Numbers whose sum of every K consecutive digits is equal