输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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) {
let left = 0, right = matrix[0].length - 1, top = 0, boom = matrix.length - 1;//记录四个角的位置
let list = []
while ((right > left) && (boom > top)) {
for (let i = left; i <= right; i++) {//从左到右
list.push(matrix[top][i]);
}
for (let i = top + 1; i <= boom; i++) {//上到下
list.push(matrix[i][right]);
}
for (let i = right - 1; i >= left; i--) {//右到左
list.push(matrix[boom][i]);
}
for (let i = boom - 1; i > top; i--) {//下到上
list.push(matrix[i][left]);
}
left++;
right--;
top++;
boom--;
}
if ((boom === top) && (left < right)) {//单独剩下一行的情况
for (let i = left; i <= right; i++) {
list.push(matrix[top][i]);
}
}
if ((left === right) && (boom > top)) {//单独剩下一列的情况
for (let i = top; i <= boom; i++) {
list.push(matrix[i][left]);
}
}
if ((boom === top) && (right === left)) {//单独剩下一个元素的情况
list.push(matrix[left][boom]);
}
return list;
}
网友评论