如何通过javascript获取下图的螺旋方向数
如何通过 javascript 或 jquery 获取上图的螺旋方向数
请帮我
我希望通过螺旋方向获得二维数组的索引号
我希望得到这样的数字序列
3X3 -> 0,1,2,5,8,7,6,3,4
4X5 -> 0,1,2,3,4,9,14,19,18,17,16,15,10,5,6,7,8,13,12,11
如何通过javascript获取下图的螺旋方向数
如何通过 javascript 或 jquery 获取上图的螺旋方向数
请帮我
我希望通过螺旋方向获得二维数组的索引号
我希望得到这样的数字序列
3X3 -> 0,1,2,5,8,7,6,3,4
4X5 -> 0,1,2,3,4,9,14,19,18,17,16,15,10,5,6,7,8,13,12,11
从您的问题来看,您的网格存储的形式并不完全清楚;我假设一个 HTML 表格。假设你的螺旋规则是尽可能向右走,然后向下,然后向左,然后向上,根据需要重复,在 jQuery/JS 中实现的以下(当然很简单)算法应该为你找到正确的路径:
$.getCellAtIndex = function (row, col) {
return $("table tr")
.filter(":nth-child(" + row + ")")
.find("td")
.filter(":nth-child(" + col + ")")
.not(".highlight")
.first();
}
$(function () {
var path = [];
var row = 1;
var col = 1;
while (true) {
var nextCell = $.getCellAtIndex(row, col);
nextCell.addClass("highlight");
path.push(nextCell);
// Move right, if possible
if ($.getCellAtIndex(row, col + 1).length > 0) {
col++;
}
// Otherwise move down
else if ($.getCellAtIndex(row + 1, col).length > 0) {
row++;
}
// Otherwise move left
else if ($.getCellAtIndex(row, col - 1).length > 0) {
col--;
}
// Otherwise move up
else if ($.getCellAtIndex(row - 1, col).length > 0) {
row--;
}
// Can't spiral anymore:
// Output path as comma-separated string
else {
$("span").text(function () {
return path.map(function (elem) {
return $(elem).text();
}).join(', ');
});
break;
}
}
});
只需存储 currentx
和y
in 变量,并保持“当前方向” indx
和dy
start from(0, 0)
和 with direction (1, 0)
。
现在算法是
y*width+x
x+dx, y+dy
无效或已访问过,请右转t=dy; dy=dx; dx=-t;
x+=dx; y+=dy;
并重复此width * height
步骤。
function a(quantity){
var arr = new Array(quantity * quantity);
var result = [];
var start = false;
for (var i = 0; i < arr.length; i++) {
var step = i % quantity;
if (step === 0) {
result.push([]);
start = !start;
}
if (start) {
result[result.length - 1].push(i + 1);
} else {
result[result.length - 1].unshift(i + 1);
}
}
return result;
}
console.log(a(3));