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

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

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
};
全部评论

相关推荐

06-11 13:34
门头沟学院 C++
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务