我被困在这个地方,在那里,我无法继续前进。问题是这样的。给定一个n x n
数组,将从最外层元素排列的数组元素返回到中间元素,顺时针方向行进。
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
为了更好地理解,请连续按照下一个数组的编号:
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
此图片将更清楚地说明事情:
到目前为止我的尝试是:
arr = [[1, 2, 3], [3, 4]];
var n = arr[0].length;
var i = 0, j = 0;
var fa = [];
var count = 0;
var direction = "right";
console.log(n);
while (fa.length < n * n) {
fa.push(`${i}, ${j}`);
if (j == n - 1 && i < n - 1) {
direction = "down";
} else if (j == 0 && i != 0) {
direction = "up";
} else if (i == n - 1) {
direction = "left";
} else if (i == 0) {
direction = "right";
}
switch (direction) {
case "right":
j++;
break;
case "left":
j--;
break;
case "up":
i--;
break;
case "down":
i++;
break;
}
if (count++ == 15)
break;
}
console.log(fa);
我有点不确定如何继续。我需要知道两件事。
答案 0 :(得分:2)
以下是我为此问题所做的工作。你可以看到我如何跟踪最小和最大col和row值。我不确定你在代码中到底是怎么做的,但希望这会有所帮助。
var m = 4;
var n = 4;
var board = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
var result = [];
var dir = 'right';
var imin = 0;
var imax = m - 1;
var jmin = 0;
var jmax = n - 1
var i = imin;
var j = jmin;
var done = false;
while (!done)
{
switch (dir)
{
case 'right':
i = imin;
j = jmin;
for (j; j <= jmax; j++)
result.push(board[i][j]);
console.log(result);
dir = 'down';
imin++;
break;
case 'left':
i = imax;
j = jmax;
for (j; j >= jmin; j--)
result.push(board[i][j]);
console.log(result);
dir = 'up';
imax--;
break;
case 'down':
i = imin;
j = jmax;
for (i; i <= imax; i++)
result.push(board[i][j]);
console.log(result);
dir = 'left';
jmax--;
break;
case 'up':
i = imax;
j = jmin;
for (i; i >= imin; i--)
result.push(board[i][j]);
console.log(result);
dir = 'right';
jmin++;
break;
}
if (imin > imax || jmin > jmax)
done = true;
}
console.log(result);
答案 1 :(得分:0)
很抱歉这么晚。
我对这个问题的解决办法是
arr = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16],
];
function rotate(arr) {
copy = [];
rows = arr.length;
for(i = 0; i < rows; i++) {
cols = arr[i].length;
for(j = 0; j < cols; j++) {
if(copy[cols - 1 - j] === undefined) copy[cols - 1 - j] = [];
copy[cols - 1 - j][i] = arr[i][j];
}
}
return copy;
}
res = [];
do {
res = res.concat(arr.shift());
arr = rotate(arr);
} while(arr.length);
console.log(res);