1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class SpiralMatrixII { public int[][] generateMatrix(int n) { if (n < 0) { return null; } int[][] matrix = new int[n][n]; if (n == 0) { return matrix; }
int val = 1;
int x = 0; int y = 0; int w = n; while (w > 0) { for (int i = 0; i < w - 1; i++) { matrix[x][y++] = val++; }
for (int i = 0; i < w - 1; i++) { matrix[x++][y] = val++; }
for (int i = 0; i < w - 1; i++) { matrix[x][y--] = val++; }
for (int i = 0; i < w - 1; i++) { matrix[x--][y] = val++; }
w = w - 2; x++; y++; } if (n % 2 == 1) { matrix[n / 2][n / 2] = val; } return matrix; } }
|