2015-04-16 100 views
1

所以我試圖獲得所有可以放入Sudoku單個正方形的條目。我有一個9x9二維陣列,它進一步分爲3x3子陣列。我想寫一個方法,在其參數中取一行&列組合並返回可以在該特定位置進行的所有可能條目。 我的方法的前2個for-loops採用指定的整個行的所有已存在的非零值並將它們存儲在數組中(alreadyInUse),這將在稍後階段用於計算哪些號碼尚未使用。第三個for循環應該使用行,列組合,找到特定的子數組並將其條目添加到alreadyInUse數組中。從給定的行(x),列(y),找到2D 9x9陣列的3x3子陣列

有沒有什麼方法可以找到使用給定的行,列的2D數組的子列的行,列?

// Method for calculating all possibilities at specific position 
public int[] getPossibilities(int col, int row){ 
    int [] possibilities; 
    int [] alreadyInUse = null; 
    int currentIndex = 0; 
    if(sudoku[row][col] != 0){ 
     return new int[]{sudoku[col][row]}; 
    } 
    else{ 
     alreadyInUse = new int[26]; 
     //Go into Row x and store all available numbers in an alreadyInUse 
     for(int i=0; i<sudoku.length; i++){ 
      if(sudoku[row][i] !=0){ 
       alreadyInUse[currentIndex] = sudoku[row][i]; 
       currentIndex++; 
      } 
     } 
     for(int j=0; j<sudoku.length; j++){ 
      if(sudoku[j][col] !=0){ 
       alreadyInUse[currentIndex] = sudoku[j][col]; 
       currentIndex++; 
      } 
     } 
     for(int k=...??? 

    } 
     return possibilities; 
} 
+0

數獨算法我相信? –

+0

@ tgm1024,是的,先生。 –

+0

大聲笑。對於這個跛腳的問題抱歉。代碼示例本身具有'sudoku [] []'。有些日子...... –

回答

2

您可以使用模數過濾出子數組。例如,一種方法是使用表達式n - (n % 3)。例如,如果行是第8列(0索引數組中的最後一列),則此表達式將返回6.它將爲返回6列6,但它將返回3列5的列表。

然後,一旦你有左上角的單元格,你可以使用嵌套循環遍歷所有9個單元格,一次三個。

下面是相關的代碼:

int x_left = (row - (row % 3)); 
int y_top = (col - (col % 3)); 
for(int i=0; i<3; i++) { 
    for(int j=0; j<3; j++) { 
    if(sudoku[i + x_left][j + y_top] != 0) { 
     alreadyInUse[currentIndex] = sudoku[i + x_left][j + y_top]; 
     currentIndex++; 
    } 
    } 
} 
+0

這就像一個魅力嘿。謝謝一堆! –