对编码非常陌生,所以请多多包涵。我正试图在 Codewars 上解决这个 Kata:https://www.codewars.com/kata/snail/train/javascript
基本上给定一个像
这样的数组[
[1, 2, 3, 4],
[12,13,14,5],
[11,16,15,6],
[10,9, 8, 7]
];
它将返回 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
。
一条蜗牛轨迹在矩阵外部和内部盘旋。
我只是解决矩阵为 n x n 的情况,其中 n > 1 且现在为偶数。
我通过在函数外声明 outputarray 使其工作,但我希望在函数内声明该数组,因此包含以下行:var outputarray = outputarray || [];
不确定我哪里出错了。
snail = function(array) {
if (array.length == 0) {
return outputarray
}
var n = array[0].length - 1;
var outputarray = outputarray || [];
for (var i = 0; i <= n; i++) {
outputarray.push(array[0].splice(0, 1));
}
for (var i = 1; i <= n; i++) {
outputarray.push(array[i].splice(n, 1));
}
for (var i = n - 1; i >= 0; i--) {
outputarray.push(array[n].splice(i, 1));
}
for (var i = n - 1; i > 0; i--) {
outputarray.push(array[i].splice(0, 1));
}
array.pop();
array.shift();
snail(array);
}
最佳答案
这是一种不改变输入 array
的非递归方法。它通过跟踪左上坐标 x, y
和螺旋的大小 n
来工作。
snail = function(array) {
const { length } = array;
const result = [];
let x = 0;
let y = 0;
let n = length;
while (n > 0) {
// travel right from top-left of spiral
for (let i = x; i < x + n; ++i) result.push(array[y][i]);
// shrink spiral and move top of spiral down
n--; y++;
// travel down from top-right of spiral
for (let i = y; i < y + n; ++i) result.push(array[i][x + n]);
// travel left from bottom-right of spiral
for (let i = x + n - 1; i >= x; --i) result.push(array[y + n - 1][i]);
// shrink spiral
n--;
// travel up from bottom-left of spiral
for (let i = y + n - 1; i >= y; --i) result.push(array[i][x]);
// move left of spiral right
x++;
}
return result;
}
console.log(snail([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));
关于javascript - Codewars Kata 上的递归问题 - Snail Trail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078536/