从给定的行(X),列(Y),找到一个2D 9x9的阵列的子阵列3x3的(From given row

2019-10-22 16:40发布

所以我试图让所有可以放入数独单方可能的条目。 我有一个9x9的2D阵列,其被进一步分成3x3的子阵列。 我想写的是发生在其参数的行和列组合,返回,可以在特定位置上的所有可能的条目的方法。 第一2 for循环我的方法的需要在阵列中(alreadyInUse)整行&整列中指定,所有的已经存在的非零值,并存储它们,这将在稍后阶段被用来找出数字尚未使用。 第三for循环应使用行,列组合,找到特定子数组,并添加其条目到alreadyInUse阵列。

有二维阵列的任何方法来找到该行,该子数组列使用给定的行,列?

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

Answer 1:

您可以使用模滤除子阵列。 例如,一种方法来做到这将是使用表达式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++;
     }
  }
}


文章来源: From given row(x),column(y), find 3x3 subarray of a 2D 9x9 array