-2

javascriptで下の画像のらせん方向番号を取得するにはどうすればよいですか

らせん方向番号

javascriptまたはjqueryで上の画像のらせん方向番号を取得するにはどうすればよいですか

私を助けてください

らせん方向で2次元配列のインデックス番号を取得したい

このように数列を取得したいと思います

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

4

3 に答える 3

2

jsFiddle デモ

あなたの質問から、グリッドがどのような形式で保存されているかは完全に明確ではありません。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;
        }
    }
});
于 2013-12-26T08:54:34.153 に答える