中等

image.png

思路:

  1. 首先确定边界,top、right、bottom、left、
  2. 然后开始遍历存值:
  • top为0,开始从left到right存值,然后top+1
  • right为n-1,开始从top到bottom存值,然后right-1
  • bottom为n-1,开始从right到left存值,然后bottom-1
  • left为0,开始从bottom到top存值,然后left+1
  • 循环…
    1. let n = 5;
    2. var generateMatrix = function (n) {
    3. const matrix = new Array(n);
    4. for (let i = 0; i < n; i++) {
    5. //生成空的数组
    6. matrix[i] = new Array(n);
    7. }
    8. console.log(matrix);
    9. let num = 1;
    10. let left = 0, right = n - 1, top = 0, bottom = n - 1;
    11. while (num <= n * n) {
    12. for (let i = left; i <= right; i++) {
    13. console.log('1*--', top, i, '=' + num);
    14. matrix[top][i] = num
    15. num++
    16. }
    17. top++;
    18. for (let i = top; i <= bottom; i++) {
    19. console.log('2*--', i, right, '=' + num);
    20. matrix[i][right] = num
    21. num++;
    22. }
    23. right--;
    24. for (let i = right; i >= left; i--) {
    25. console.log('3*--', bottom, i, '=' + num);
    26. matrix[bottom][i] = num
    27. num++;
    28. }
    29. bottom--;
    30. for (let i = bottom; i >= top; i--) {
    31. console.log('4*--', i, left, '=' + num);
    32. matrix[i][left] = num
    33. num++;
    34. }
    35. left++;
    36. console.log(num, 'left =' + left, 'right =' + right, " top =" + top, "bottom =" + bottom);
    37. }
    38. // return matrix;
    39. };
    40. console.log(generateMatrix(n));