繁体   English   中英

从给定的row(x),column(y)中找到2D 9x9数组的3x3子数组

[英]From given row(x),column(y), find 3x3 subarray of a 2D 9x9 array

因此,我正在尝试获取可放入Sudoku单方格中的所有可能的条目。 我有一个9x9 2D数组,该数组又分为3x3子数组。 我想编写一个在其参数中采用行和列组合的方法,并返回可以在该特定位置进行的所有可能的输入。 我的方法的前2个for循环将指定的整个行和整个列中的所有已经存在的非零值都存储在一个数组中(alreadyInUse),这将在以后的阶段用于确定什么数字尚未使用。 第三个for循环应使用row,column组合查找特定的子数组,并将其条目添加到已经使用的数组中。

有没有办法使用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;
} 

您可以使用模数来滤除子数组。 例如,一种实现方法是使用表达式n - (n % 3) 例如,如果row是第8列(索引数组为0的最后一列),则此表达式将返回6。第6列还将返回6,但第5列将返回3。

然后,一旦有了左上角的单元格,就可以使用嵌套循环遍历所有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++;
     }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM