什么螺旋矩阵:螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。
如下: 最终组成的结果是
[
1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
]
function spiralOrder(matrix) {
let result = [];
let num = 1;
while (num) {
if (num === 1) {
result.push(...matrix.shift());
} else if (num === 2) {
matrix.forEach((it) => {
result.push(it.pop());
});
} else if (num === 3) {
result.push(...matrix.pop().reverse());
} else if (num === 4) {
for (var i = matrix.length - 1; i > -1; i--) {
result.push(matrix[i].shift());
}
}
if (!matrix.length || !matrix[0].length) {
return result;
}
num += 1;
if (num > 4) {
num = 1;
}
}
}
console.log(
spiralOrder([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
])
);
|