Question prototype:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =3
,
You shoshould return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
Basic Ideas:
We noticed that the position of each start operation is the diagonal line. When a circle is printed, the column coordinate is first accumulated 1, then the row coordinate is accumulated 1, and then the column coordinate class is reduced by 1, and the last row coordinate is subtracted by 1. Repeat the preceding operation until the end.
Public int [] [] generateMatrix (int n) {int [] [] num = new int [n] [n]; int layer = 0; // number of layers enclosed by int I = 1; // count int row = 0; int column = 0; while (true) {while (column
= Layer) {num [row] [column] = I; I ++; column --;} column ++; row --; layer ++; // Add the number of circles to a while (row> = layer) {num [row] [column] = I; I ++; row --;} if (layer> (n + 1)/2) break; // reassign the start row = layer; column = layer;} return num ;}