Have no idea what's your question but here is a short method that's placing a boarder to a matrix. You could use the `a` as index for the B array. private static void placeBoarders(int[][] matrix, int n) { int a = 0; for (int i = 0; i < 4 * (n-1); i++) { switch (i/(n - 1)) { case 0: matrix[i%(n-1)][0] = a; break; case 1: matrix[n-1][i%(n-1)] = a; break; case 2: matrix[(n - 1) - i%(n-1)][n-1] = a; break; case 3: matrix[0][(n-1) - i%(n-1)] = a; break; default: throw new IndexOutOfBoundsException(); } a++; } } The logic I've used here is that if I split the boarder to four equal chunks and I start from (top left -> bottom left -> bottom right -> top right -> top left) then I will have four pieces of size n-1. If you write it dawn on a paper then it will take like 5 mins to calculate the indexes. For the opposite direction (top left -> top right -> bottom right -> bottom left -> top left) you should swap the matrix indexes just like this: matrix[i%(n-1)][0] >> matrix[0][i%(n-1)] matrix[n-1][i%(n-1)] >> matrix[i%(n-1)][n-1] matrix[(n - 1) - i%(n-1)][n-1] >> matrix[n-1][(n - 1) - i%(n-1)] matrix[0][(n-1) - i%(n-1)] >> matrix[(n-1) - i%(n-1)][0]