首页 > 代码库 > 顺时针打印矩阵
顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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)); } }
顺时针打印矩阵
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。