59. 螺旋矩阵 II(JavaScript)

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

示例:

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

思路:

这和上一道题很类似:54.螺旋矩阵

1、初始化结果矩阵

2、设置上下左右4个变量

3、设置当前要添加的元素

4、逐个添加元素

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
  let result = []
  for (let i = 0; i < n; i ++) {
    result.push(Array(n))
  }
  let left = 0,
      right = n - 1,
      top = 0,
      bottom = n - 1,
      curr = 1
  while (top <= bottom && left <= right) {
    for (let i = left; i <= right; i++) {
      result[top][i] = curr++
    }
    if (++top > bottom) break
    for (let j = top; j <= bottom; j++) {
      result[j][right] = curr++
    }
    if (--right < left) break
    for (let i = right; i >= left; i--) {
      result[bottom][i] = curr++
    }
    if (--bottom < top) break
    for (let j = bottom; j >= top; j--) {
      result[j][left] = curr++
    }
    if (++left > right) break
  }
  return result
};

 

你可能感兴趣的:(leetcode,中等题,medium,javascript)