螺旋方阵JavaScript的元素
我们需要编写一个JavaScript函数,该函数接受像这样的文字数组的二维(必要时为方阵)数组-
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
该函数应构造一个新数组,该数组从位置(0,0)开始以螺旋形式从输入数组中获取元素,并返回该一维数组。
因此,对于此阵列,螺旋线应类似于-
const output = [1, 2, 3, 6, 9, 8, 7, 4, 5];
我们将创建一个临时变量,该变量指向当前行和当前列的开头和结尾。
这样,我们可以迭代地递增开始行和开始列,并递减结束行和结束列,其方式是向矩阵中心旋转。
示例
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
const spiral = (arr = []) => {
if (!arr || arr.length === 0) {
return [];
};
let startRow = 0;
let startCol = 0;
let res = [];
let endCol = arr[0].length - 1;
let endRow = arr.length - 1;
while (startRow <= endRow && startCol <= endCol) {
for (let i = startCol; i <= endCol; i++) {
res.push(arr[startRow][i]);
}
startRow++;
for (let i = startRow; i <= endRow; i++) {
res.push(arr[i][endCol]);
}
endCol--;
if (startRow <= endRow) {
for (let i = endCol; i >= startCol; i--) {
res.push(arr[endRow][i]);
}
endRow--;
}
if (startCol <= endCol) {
for (let i = endRow; i >= startRow; i--) {
res.push(arr[i][startCol]);
} startCol++;
}
}
return res;
};
console.log(spiral(arr));输出结果
控制台中的输出将是-
[ 1, 2, 3, 6, 9, 8, 7, 4, 5 ]