题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路:
打印循环结束的条件是每个轮回开始点下标的2倍超过矩阵的大小
function printMatrix(matrix)
{
// write code here
if(matrix == null || matrix[0].length == 0){
return ;
}
let row = matrix.length;
let col = matrix[0].length;
let start = 0;
let res = [];
while(col > start*2 && row > start*2){
let endx = col-1-start;
let endy = row-1-start;
//从左至右
for(let i = start; i <= endx; i++){
res.push(matrix[start][i]);
}
//从上至下
if(start < endy){
for(let i = start+1; i <= endy; i++){
res.push(matrix[i][endx])
}
}
//从右向左
if(start < endx && start < endy){
for(let i = endx-1; i >= start; i--){
res.push(matrix[endy][i])
}
}
//从下至上
if(start < endx && start < endy -1){
for(let i = endy - 1; i >= start + 1; i--){
res.push(matrix[i][start]);
}
}
start++;
}
return res;
}