# 螺旋矩阵 II

  1. 螺旋矩阵 II

来源:力扣(LeetCode) 链接 (opens new window):https://leetcode.cn/problems/add-two-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

github (opens new window)

# 问题

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

# 思路

var generateMatrix = function (n) {
  let top = 0,
    left = 0,
    right = n - 1,
    bottom = n - 1;

  let index = 1;
  let max = n * n;
  let arr = [];

  let a = new Array(n).fill("");

  for (let i = 0; i < n; i++) {
    arr.push([...a]);
  }

  while (index <= max) {
    for (let i = left; i <= right; i++) {
      arr[top][i] = index++;
    }
    top++;
    for (let i = top; i <= bottom; i++) {
      arr[i][right] = index++; // top to bottom.
    }
    right--;
    for (let i = right; i >= left; i--) {
      arr[bottom][i] = index++; // right to left.
    }
    bottom--;
    for (let i = bottom; i >= top; i--) {
      arr[i][left] = index++; // bottom to top.
    }
    left++;
  }
  return arr;
};
陕ICP备20004732号-3