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

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

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

相关推荐

fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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