顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
 
function printMatrix(matrix)
{
    // write code here
    var rows;
    var cols;
    var i,j;
    var result = [];
    if(matrix.length === 0 ){
        return result;
    }else{
//读取矩阵第一行的元素 cols
= matrix[0].length; if(cols > 0){ i = 0; while(i < cols){ result.push(matrix[0][i]); i++; } matrix.shift(); } rows = matrix.length; //读取矩阵最后一列元素 if(rows > 0){ cols = matrix[0].length; j = 0; while(j < rows && cols != 0){ result.push(matrix[j][cols-1]); matrix[j].pop(); j++; } }else{ return result; } rows = matrix.length; //读取最后一行的元素 if(rows > 0){ cols = matrix[0].length; j = cols-1; while(j >= 0 && cols != 0){ result.push(matrix[rows-1][j]); j--; } matrix.pop(); }else{ return result; } rows = matrix.length; //读取第一列的元素 if(rows > 0){ cols = matrix[0].length; i = rows - 1; while(i >= 0 && cols != 0){ result.push(matrix[i][0]); matrix[i].shift(); i--; } }else{ return result; } return result.concat(printMatrix(matrix)); } }
 
原文地址:https://www.cnblogs.com/deerfig/p/6878948.html