const result = [];
const printEdge = (matrix, tR, tC, dR, dC) => {
console.log(matrix, tR, tC, dR, dC);
// 子矩阵只有一行时
if(tR === dR){
for(let i = tC; i <= dC; i++){
result.push(matrix[tR][i]);
}
}else if(tC === dC){ // 子矩阵只有一列时
for(let i = tR; i <= dR; i++){
result.push(matrix[i][tC]);
}
}else{
let curC = tC;
let curR = tR;
// 循环四次,每次打印三个,外层一圈打印完毕
// 1,2,3 ->
// 4, 8, 12 ->
// 16, 15, 14 ->
// 13, 9, 5
// 如此循环
while(curC !== dC){
result.push(matrix[tR][curC]);
curC++;
}
while(curR !== dR){
result.push(matrix[curR][dC]);
curR++;
}
while(curC !== tC){
result.push(matrix[dR][curC]);
curC--;
}
while(curR !== tR){
result.push(matrix[curR][tC]);
curR--;
}
}
}
const handleArr = (matrix) => {
let tR = 0;
let tC = 0;
let dR = matrix.length - 1;
let dC = matrix[0].length - 1;
// 外层转圈,坐标[0, 0](1), [3,3](16)
// -> [1, 1](6), [2, 2](11)
while(tR <= dR && tC <= dC){
printEdge(matrix, tR++, tC++, dR--, dC--);
}
}
handleArr(matrix);
console.log(result);