剑指Offer JZ19 顺时针打印矩阵(JavaScript)

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M 热度指数:894547
本题知识点: 数组

题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.
示例1
输入
[[1,2],[3,4]]
返回值
[1,2,4,3]

思路:不断收缩边界值,需要非常注意判断条件,否则会漏掉或者多读
left <= right && top <= bottom,循环条件,同时满足两个边界,才能保证不重复读取,需要小于且等于,才能保证不漏读

if(left > right || top > bottom ) break ,这个很关键,及时break才能保证不重复读取

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

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/115143442