Skip to content

JZ29 顺时针打印矩阵

题目描述

image-20220302235643863

示例

image-20220302235655237

代码

js
/*
转着圈打印,先打印一圈
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

这个例子只有两层,可以用矩阵的左上角和右下角唯一表示一个矩阵
设左上角坐标为 (lx, ly),右下角坐标为(rx, ry)

第一步:打印 1 2 3 4
第二步:打印 8 12 16
第三步:打印 15 14 13
第四步:打印 9 5
*/
function printMatrix(matrix)
{
    // write code here
    
    let result = [] 
    if( matrix.length === 0 ){
        return result
    }
    
    let lx = 0 // 左上角 x 坐标
    let ly = 0 // 左上角 y 坐标
    let rx = matrix.length - 1 // 右下角 x 坐标
    let ry = matrix[0].length - 1 // 右下角 y 坐标
    
    while( lx <= rx && ly <= ry ){
        
        // 循环打印,当 lx越界或者 ly越界时,打印完毕
        // 每打印一圈,往里缩放一个索引
        print(lx++, ly++, rx--, ry--, matrix, result)
    }
    
    return result
    
    // 转圈打印
    function print(lx, ly, rx, ry, matrix, ret){
        
        // 从左到右打印 1 2 3 4
        for(let j = ly; j <=ry; j++) {
            ret.push( matrix[lx][j] )
        }
        
        // 从上到下打印 8 12 16
        for( let i = lx+1; i <=rx; i++ ){
            ret.push( matrix[i][ry] )
        }
        
        let h = rx - lx + 1 //看一下总共有几行
        
        if( h > 1 ){ // 只有一行,不需要第三步
            // 打印 15 14 13
            for( let rj = ry - 1; rj >=  ly; rj-- ){
                ret.push( matrix[rx][rj] )
            }
        }
        
        
        let w = ry - ly + 1 // 看一下总共有几列
        
        if( w > 1 ){ // 只有第一列 不需要第四步
            // 打印 9 5
            for( let ri = rx - 1; ri >= lx + 1; ri-- ){
                ret.push( matrix[ri][ly] )
            }
        }
        
    }
    
}
module.exports = {
    printMatrix : printMatrix
};

题目来源

JZ29 顺时针打印矩阵