Construct a unique matrix n x n for an input n

Vipul Gupta
2 min readMay 11, 2021

This is marked as Hard on the geek's platform.

Given an odd integer n, find a matrix of size n x n with the following conditions:

  1. Each cell contains an integer from 1 and n (inclusive).
  2. No integer appears twice in the same row or the same column.
  3. All 1’s must be at every possible distance from the center of the matrix. The center of a n x n square is cell ((n-1)/2, (n-1)/2) for odd n.

Example :


Input : n = 1
Output : 1

Input : n = 3
Output: 3 2 1
1 3 2
2 1 3

Input : n = 5
Output : 5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5

This is a very simple problem based on observation skills.

Steps:

  1. Place all the 1’s at their right position.

Take 2 pointers left=0 and right= nums-1 for columns, and alternatively put 1, while traversing rows(0 to nums-1).

do right=right-1 and left = left+1

_ _ _ _ 1 
1 _ _ _ _
_ _ _ 1 _
_ 1 _ _ _
_ _ 1 _ _

2. Now for all the ones put the values from (1–5) at their place. Columnwise put the counting 1–5 like:

5 _ _ 4 1 
1 _ _ 5 2
2 _ _ 1 3
3 1 _ 2 4
4 _ 1 3 5

Let's jump to the coding part:

package com.geeks.array;import java.util.Arrays;public class ConstructMatrixNXN {public static void main(String[] args) {int num = 10;constructMatrix(num);}public static void constructMatrix(int num) {int matrix[][] = new int[num][num];int right = num - 1;int left = 0;for (int i = 0; i < num; i++) {if (i % 2 == 0) {    matrix[i][right] = 1;    fillElement(i, right, matrix);    right--;} else {      matrix[i][left] = 1;      fillElement(i, left, matrix);      left++;
}
} for (int[] row : matrix) { System.out.println(Arrays.toString(row)); }}public static void fillElement(int row, int col, int mat[][]) {int count = 1; while (count != mat[0].length) { int rowTemp = (row + 1) % mat[0].length; mat[rowTemp][col] = ++count; row++; } }}output:
[10, 8, 6, 4, 2, 3, 5, 7, 9, 1]
[1, 9, 7, 5, 3, 4, 6, 8, 10, 2][2, 10, 8, 6, 4, 5, 7, 9, 1, 3][3, 1, 9, 7, 5, 6, 8, 10, 2, 4][4, 2, 10, 8, 6, 7, 9, 1, 3, 5][5, 3, 1, 9, 7, 8, 10, 2, 4, 6][6, 4, 2, 10, 8, 9, 1, 3, 5, 7][7, 5, 3, 1, 9, 10, 2, 4, 6, 8][8, 6, 4, 2, 10, 1, 3, 5, 7, 9][9, 7, 5, 3, 1, 2, 4, 6, 8, 10]

Happy Coding!

--

--