题解 | #顺时针打印矩阵#

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

function printMatrix(matrix) {
  // write code here
  if (matrix.length === 0 || matrix[0].length === 0) return [];
  let left = 0;
  let right = matrix[0].length - 1;
  let bottom = 0;
  let top = matrix.length - 1;
  const res = [];
  while (left <= right && top >= bottom) {
    for (let i = left; i <= right; i++) {
      res.push(matrix[bottom][i]);
    }
    bottom++;
    if (bottom > top) break;

    for (let i = bottom; i <= top; i++) {
      res.push(matrix[i][right]);
    }
    right--;
    if (left > right) break;

    for (let i = right; i >= left; i--) {
      res.push(matrix[top][i]);
    }
    top--;
    if (bottom > top) break;

    for (let i = top; i >= bottom; i--) {
      res.push(matrix[i][left]);
    }
    left++;
    if (left > right) break;
  }
  return res;
}
module.exports = {
  printMatrix: printMatrix,
};

全部评论

相关推荐

01-24 12:50
门头沟学院 C++
投票
菜狗二号:还有啥想的 指定国有行啊,去了就开始幸福美满的生活了,选华子不是折腾自己么,最终财富积累度是差不多的,但是幸福指数是相差甚远的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务