首页 > 试题广场 >

转圈打印矩阵

[编程题]转圈打印矩阵
  • 热度指数:1556 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整型矩阵matrix,请按照顺时针转圈的方式打印它。
示例1

输入

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

输出

[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

备注:
如果你愿意一层一层的剥开我的心
function printMatrix( matrix ) {
    // write code here
    const res = []
    if(matrix.length==0) return []
     let top = 0,bottom = matrix.length-1,right= matrix[0].length-1,left=0
    while(left<right&&top<bottom){
    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 ++
        bottom--
        left++
        right--
    }
   if(left==right){
       for(let i = top;i<=bottom;i++) res.push(matrix[i][right])//右层
   } else if(top == bottom){
      for(let i= left;i<=right;i++) res.push(matrix[top][i])//上层
   }
     return res
}

发表于 2020-12-25 12:04:45 回复(0)

问题信息

难度:
1条回答 3484浏览

热门推荐

通过挑战的用户