image.png

解题思路

image.png

  1. public int[][] generateMatrix(int n) {
  2. int l = 0, r = n - 1, t = 0, b = n - 1;
  3. int[][] mat = new int[n][n];
  4. int num = 1, tar = n * n;
  5. while(num <= tar){
  6. for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
  7. t++;
  8. for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
  9. r--;
  10. for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
  11. b--;
  12. for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
  13. l++;
  14. }
  15. return mat;
  16. }