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
| class Solution { public int[][] generateMatrix(int n) { int[][] result = new int[n][n]; int top = 0, bottom = n - 1; int left = 0, right = n - 1; int num = 1;
while (top <= bottom && left <= right) { for (int i = left; i <= right; i++) { result[top][i] = num++; } top++;
for (int i = top; i <= bottom; i++) { result[i][right] = num++; } right--;
if (top <= bottom) { for (int i = right; i >= left; i--) { result[bottom][i] = num++; } bottom--; }
if (left <= right) { for (int i = bottom; i >= top; i--) { result[i][left] = num++; } left++; } }
return result; } }
|