暗风吹雨入寒窗
理解是偶然,误解是常态。

【算法】二维数组的外层顺序遍历思路

远浅发表于: 2021-06-25 11:11分类: 技术

思路: 获取上边界,下边界,左边界,右边界。

从左到右遍历一次后收窄上边界。

从上往下遍历一次后收窄右边界。

从右往左遍历一次后收窄下边界。

从下往上遍历一次后收窄左边界。

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
  if (matrix.length == 0) return [];
  const row = matrix.length; // 行
  const col = matrix[0].length; // 列
  const size = row * col; // 行x列 = 个数
  const res = [];
  let top = 0;
  let right = col - 1;
  let bottom = row - 1;
  let left = 0;
  while (res.length != size) {
    // 从左 - 右边 遍历一次之后 上策边界收窄
    for (let index = left; index <= right; index++) {
      res.push(matrix[top][index]);
    }
    top++;
    // 从上到下 遍历一次后 右侧边界收窄;
    for (let index = top; index <= bottom; index++) {
      res.push(matrix[index][right]);
    }
    right--;
    if (res.length == size) break;
    // 从 右 - 左 下侧边界收窄
    for (let index = right; index >= left; index--) {
      res.push(matrix[bottom][index]);
    }
    bottom--;
    // 从下往上 左侧边界收窄
    for (let index = bottom; index >= top; index--) {
      res.push(matrix[index][left]);
    }
    left++;
  }
  return res;
};

赠人玫瑰, 手有余香。🌹
打赏
特别鸣谢
感谢以下用户对本文的支持与鼓励
加载打赏用户中
发表评论
文章评论
暂无任何评论,快去发表吧~