2013-01-07 71 views
0

那么我想这个问题做的是给定数字的网格我想有有一个即使在电网号的位置,并通过具有一个位置时,它会发现所有其他甚至连接到它的元素。识别连接数组中的元素

此图为我试图来形容。图片假设我有 enter image description here

enter image description here

这里的位置是我的代码我写了我几乎可以肯定,它的作品我只是想看看是否有无论如何,我可以把它更高效的

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

(我认为这将是更直观,如果6个是在1,2,而不是0,1) – cwallenpoole

+0

@cwallenpoole,几乎所有* *在计算机科学中使用基于0的索引。使用基于1的索引不会很直观。 – SimonC

+0

@SimonC目前,他正在从左至右为0,0的顶部开始和右下方是2,2(这就是为什么他是用0,1 6)。相反,右下角应该是0,0。这将使第二个x指数(1)和第三个y指数(2)成为6。现在,您可以尝试去争论,它应该以我们定位像素为导向,而不是像我们定位坐标系一样,但我不相信这一点。 – cwallenpoole

回答

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); 
} 

这将节省您至少/ 4您的阵列的查找和可能的呼叫数量为isEven()isCracked()

+0

即时通讯不知道我明白代码。既然你有iterDown()iterLeft()和iterRight()方法,但没有定义它们。另外我们如何知道已关闭? –

+0

左右下方就像是一样,只有他们会移动到左侧,右侧和下方。 – cwallenpoole

+0

你会知道下面的节点已经被检查过了,因为up方法只是迭代起来(意味着它*已经从已经在它下面检查过的节点被调用过)。 – cwallenpoole