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
| class Solution { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int loop = 0; int start = 0; int num = 1; int i,j; while(loop++ < n/2){ for(j = start ; j< n-loop ; j++){ res[start][j] = num++; } for(i = start ; i < n-loop ; i++){ res[i][j] = num++; } for( ; j >= loop; j--){ res[i][j] = num++; }
for(;i >= loop ; i--){ res[i][j]=num++; } start++; } if(n%2==1) res[start][start] = num;
return res; } }
|