[54] 螺旋矩阵

116 阅读1分钟

思路: 1.定义四个边界值,top和left都是0,right为数组的第一元素的长度-1,bottom为数组的长度-1

2.按照右下左上进行push

/*
 * @lc app=leetcode.cn id=54 lang=javascript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  if (matrix.length === 0) {
    return []
  }
  // 定义四个边界值,top和left都是0,right为数组的第一元素的长度-1,bottom为数组的长度-1
  let top = 0,
    left = 0,
    right = matrix[0].length - 1,
    bottom = matrix.length - 1
  let derection = 'right'
  let result = []
  while (left <= right && top <= bottom) {
    if (derection === 'right') {
      // 判断是右就进行for循环将数组的每一项push进去
      for (let i = left; i <= right; i++) {
        result.push(matrix[top][i])
      }
      top++
      derection = 'bottom'
    } else if (derection === 'bottom') {
      for (let i = top; i <= bottom; i++) {
        result.push(matrix[i][right])
      }
      right--
      derection = 'left'
    } else if (derection === 'left') {
      for (let i = right; i >= left; i--) {
        result.push(matrix[bottom][i])
      }
      bottom--
      derection = 'top'
    } else if (derection === 'top') {
      for (let i = bottom; i >= top; i--) {
        result.push(matrix[i][left])
      }
      left++
      derection = 'right'
    }
  }
  return result
}
// @lc code=end