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

二维矩阵按圈从最外层圈进行往内层遍历

function printMatrix(matrix)
{
    // write code here
    //最终返回的数组
    let resArr = []
    let row = matrix.length
    let column = matrix[0].length
    //定义左、上、右、下的打印范围
    let left = 0
    let right = column - 1
    let top = 0
    let bottom = row - 1
    while(left <= right && top <= bottom) {
        //从左到右
        for(let i = left; i <= right; i++) {
            resArr.push(matrix[top][i])
        }
        //从上到下,i从top+1开始,避免与之前遍历元素重复
        for (let i = top + 1; i <= bottom; i++) {
            resArr.push(matrix[i][right])
        }
        //需满足上不等于下时才能够接着遍历右到左边的元素
        if(top !== bottom) {
            //从右到左
            for (let i = right -1; i >= left; i--) {
            resArr.push(matrix[bottom][i])
            }
        }
        if(left !== right){
            //从下到上
            for (let i = bottom - 1; i > top; i--) {
                resArr.push(matrix[i][left])
            }
        }
        
        //遍历矩阵一圈后,就让左右上下索引改变
        left ++
        right --
        top ++
        bottom --
    }
    console.log(resArr)
    return resArr
}
module.exports = {
    printMatrix : printMatrix
};
全部评论

相关推荐

小马云表哥:我秋招一般是说要出国留学了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务