minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

14 -【leetcode】螺旋矩阵 #14

Open wordlex opened 3 years ago

wordlex commented 3 years ago

https://leetcode-cn.com/problems/spiral-matrix/

wucuiping commented 3 years ago
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    const rows = matrix.length // 总的行数
    const columns = matrix[0].length // 总的列数
    let left = 0
    let right = columns - 1
    let top = 0
    let bottom = rows - 1
    const result = new Array()
    while(left <= right && top <= bottom) {
        // 从左往右
        for (let col = left; col <= right; col++) {
            result.push(matrix[top][col])
        }
        // 从上往下
        for(let row=top+1; row <= bottom; row++) {
            result.push(matrix[row][right])
        }
        if (left < right && top < bottom) {
            // 从右往左
            for(let col=right-1; col>left; col--) {
                result.push(matrix[bottom][col])
            }
            // 从下往上
            for(let row=bottom; row>top; row--) {
                result.push(matrix[row][left])
            }
        }
        left++
        right--
        top++
        bottom--
    }
    return result
};
OceanApart commented 3 years ago
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let top = 0,
    right = matrix[0].length - 1,
    bottom = matrix.length - 1,
    left = 0;
  // 总数
  let amount = matrix[0].length * matrix.length
  let result = [];

  while (amount > 0) {
    // 横
    for (let i = left; i <= right && amount > 0; i++) {
      result.push(matrix[top][i])
      amount--
    }
    // 缩小边界
    top++

    // 竖
    for (let i = top; i <= bottom && amount > 0; i++) {
      result.push(matrix[i][right])
      amount--
    }
    right--

    for (let i = right; i >= left && amount > 0; i--) {
      result.push(matrix[bottom][i])
      amount--
    }
    bottom--

    for (let i = bottom; i >= top && amount > 0; i--) {
      result.push(matrix[i][left])
      amount--
    }
    left++
  }

  return result;
};