2021/03/15 每日一题 螺旋矩阵

LeetCode上螺旋矩阵,中等难度,但是很好理解,记录下解题思路

题意是要顺时针来循环,将一个二维数组转换为一维数组,之后输出


按照上图来举例,传入数组[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
循环的边界是
从上往下:
top = 0
bottom = matrix.length - 1
从左往右
left = 0
right = matrix[0].length - 1
之后需要多个循环来遍历二维数组

  1. 从左到右输出
    for (let i = left; i < right; i++) res.push(matrix[top][i])
    这样可以输出整个第一行,之后top++,然后输出列
  2. 右侧列从上往下输出
    正好上面top++之后,这个右侧列是要从新的top上来循环的
    for (let i = top; i < bottom; i++) res.push(matrix[i][right])
    这样输出之后,该列就不需要再输出了,所以right--
  3. 最下一列从右往左输出
    因为上面right--了,正好能够排除掉一个元素,所以
    for (let i = right; i > left; i--) res.push(matrix[bottom][i])
    之后还要bottom--
  4. 左侧列从下往上输出
    for (let i = bottom; i > top; i--) res.push(matrix[i][left])
    之后left++

上面基本上就形成了一个循环,在left < rightbottom > top的条件内能够循环输出元素,除了还会剩下个中心
最后中心可能剩下2种情况剩一行剩一列剩一个

  1. 剩下一行的情况
    即在这个情况中bottom === top,此时left < right,那么就从左往右输出
  2. 剩下一列的情况
    left === right,此时top < bottom,那么是从上往下输出
  3. 剩下一个的情况
    此时left === rightbottom === top,直接输出就可以了
var spiralOrder = function (matrix) {
  if (matrix.length === 0) return []
  const res = []
  let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
  while (top < bottom && left < right) {
    for (let i = left; i < right; i++) res.push(matrix[top][i])  
    for (let i = top; i < bottom; i++) res.push(matrix[i][right])  
    for (let i = right; i > left; i--) res.push(matrix[bottom][i])
    for (let i = bottom; i > top; i--) res.push(matrix[i][left])
    // 需要同时收缩
    top++
    right--
    bottom--
    left++ 
  }
  if (top === bottom) for (let i = left; i <= right; i++) res.push(matrix[top][i])
  else if (left === right) for (let i = top; i <= bottom; i++) res.push(matrix[i][left])
  return res
};

你可能感兴趣的:(2021/03/15 每日一题 螺旋矩阵)