所以我想对这个问题做的是给出一个数字网格,我希望在网格中有一个偶数的位置,通过有一个位置,它将找到连接到它的所有其他偶数元素。
这张照片显示了我想要描述的内容。图片假设我的位置 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
}
}
答案 0 :(得分: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 / 4 ,并且可能会对isEven()
和isCracked()
进行尽可能多的调用。