0

所以我试图解决这个问题是给定一个数字网格,我希望在网格中有一个偶数的位置,通过这个位置,它会找到所有其他连接到它的偶数元素。

这张照片显示了我要描述的内容。图片假设我有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

我认为您正在测试不需要测试的节点:。我会看到每个方向的四个功能:

// 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 / 4isEven()的数组查找,并可能节省尽可能多的对and的调用isCracked()

于 2013-01-07T04:20:25.020 回答