2017-06-14 45 views
0

我找不出算法來揭示掃雷艇中的空單元格。 revealCells應該接受一個單元格,然後檢查周圍的單元格並展示它們直到找到一個礦區單元,但由於某種原因,我不斷收到一個arrayindexoutofbounds異常。 Cells是電路板中的二維電池陣列。我知道我沒有檢查每一個條件,我只需要測試它是否可以工作,然後再添加其他條件。我不知道掃雷艇遞歸算法

public void revealCells(Cell cell){ 
    row = cell.getRow(); 
    column = cell.getCol(); 

    if (row < 0 || row > cells.length - 1|| column < 0 || column > cells.length - 1) return; 

    else if(cell instanceof MineCell) return;  

    else if(cell.getMineCount() == 0 && !(cell.isRevealed())){ 
     cell.reveal(); 
     revealCells(cells[row+1][column]); 
     revealCells(cells[row][column+1]); 
     revealCells(cells[row-1][column]); 
     revealCells(cells[row][column-1]); 
     revealCells(cells[row+1][column+1]); 
     revealCells(cells[row-1][column-1]); 
    } 
    else{ 
     return; 
    } 
} 
+0

'cells'是一個二維數組,但它是正方形,即寬度和高度相同?如果不是,那你爲什麼要檢查'row'和'column'對'cells.length - 1'的相同值? ---附註:你只有6次遞歸調用,但有8個相鄰單元。 – Andreas

+0

看看你的第一個條件,不應該是單元格[0] .length-1在一個地方 –

回答

1

這並不奇怪:你做遞歸調用,如:

revealCells(cells[row+1][column]); 

這意味着Java將首先獲取cells[row+1][column]。現在你沒有做任何界限檢查。方法中的邊界檢查可能是無用的,因爲您已經獲得了單元格,所以您知道它是有效的座標。

在我看來,你最好重新設計你的系統座標的工作,而不是細胞,然後提取邊界後的細胞檢查:

public void revealCells(int row, int column) { 
    if (row < 0 || row >= cells.length|| column < 0 || column >= cells[0].length) 
     return; 

    Cell cell = cells[row][column]; // now we are safe, so fetch the cell 
    if(cell instanceof MineCell) 
     return; 

    else if(cell.getMineCount() == 0 && !(cell.isRevealed())){ 
     cell.reveal(); 
     // call recursive with coordinates, not cells 
     revealCells(row-1,column-1); 
     revealCells(row-1,column); 
     revealCells(row-1,column+1); 
     revealCells(row,column-1); 
     revealCells(row,column+1); 
     revealCells(row+1,column-1); 
     revealCells(row+1,column); 
     revealCells(row+1,column+1); 
    } 
}
+1

不知道你可以在代碼中做標記。此外,你仍然錯過了兩個對角線鄰居。 –

+0

@tobias_k:謝謝指出。固定。 –

+1

感謝您的幫助! – Jack