0

したがって、この問題で私がやろうとしているのは、グリッド内の偶数の位置を取得したい数値のグリッドが与えられ、その位置を 1 つ持つことで、それに接続されている他のすべての偶数要素を見つけることです。

この図は、私が説明しようとしていることを示しています。写真は、私が6の場所にいることを前提としています ここに画像の説明を入力

ここに画像の説明を入力

これが私が書いた私のコードです 私はそれが機能することをほぼ確信しています とにかくもっと効率的にできるかどうかを見たいだけです

getLinksEven(grid,0,1);
static void getLinksEven(Server[][] grid, int k, int j)
{
    try{
        if(grid[k-1][j].isEven()&& !grid[k-1][j].isCracked()){
            grid[k-1][j].setCracked(true);
            getLinksEven(grid,k-1,j);
        }

    }
    catch(ArrayIndexOutOfBoundsException a)
    {
        //do nothing
    }
    try{
        if(grid[k][j-1].isEven()&& !grid[k][j-1].isCracked()){
            grid[k][j-1].setCracked(true);
            getLinksEven(grid,k,j-1);

        }

    }
    catch(ArrayIndexOutOfBoundsException a)
    {
        //do nothing
    }

    try{
        if(grid[k+1][j].isEven()&& !grid[k+1][j].isCracked()){
            grid[k+1][j].setCracked(true);
            getLinksEven(grid,k+1,j);

        }

    }
    catch(ArrayIndexOutOfBoundsException a)
    {
        //do nothing
    }
    try{
        if(grid[k][j+1].isEven()&& !grid[k][j+1].isCracked()){
            grid[k][j+1].setCracked(true);
            getLinksEven(grid,k,j+1);

        }

    }
    catch(ArrayIndexOutOfBoundsException a)
    {
        //do nothing
    }

}
4

1 に答える 1

2

テストする必要のないノードをテストしていると思います。各方向に4つの関数が表示されます。

// you'll need four methods just like this one. This one goes up, you'll need
// one that goes down, another left and a forth right...
static void iterUp(Server[][] grid, int k, int j)
{
    // working with a local variable is easier to read and debug...
    // you may wish to consider it.
    Server cell = grid[k][j]
    if(!cell.isEven() && !cell.isCracked())
    {
        cell.setCracked(true)
        if(k >= 1)
        {
            iterLeft(grid, k-1,j)
        }
        if(k < grid.length - 2)
        {
            iterRight(grid, k+1)
        }
        if(j < grid[k].length - 2)
        {
            iterUp(grid, k, j+1)
        }
        // no point in going down, because we know that down is checked already.
    }
}

次に、元の関数を定義します。

static void getLinksEven(Server[][] grid, int k, int j)
{
    if(grid.length < k - 1 || grid[k].length < j - 1)
    {
        throw new ArrayIndexOutOfBoundsException("Not funny.");
    }
    // if this cell isn't even... who cares?
    if(!grid[k][j].isEven()) return;

    // Send the four on their merry way.
    iterUp(grid,k,j);
    iterDown(grid,k,j);
    iterLeft(grid,k,j);
    iterRight(grid,k,j);
}

これにより、配列ルックアップの少なくとも1/4が節約され、場合によってはとへの呼び出しが同じくらい節約さisEven()れますisCracked()

于 2013-01-07T04:20:25.020 に答える