2015-04-16 51 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

这就像一个魅力嘿。谢谢一堆! –