gpt4 book ai didi

java - 如何在一定的空间输出有效数字列表?(数独)

转载 作者:行者123 更新时间:2023-11-30 12:02:01 29 4
gpt4 key购买 nike

这是我的。该方法应输出该空间中所有可用数字的数组。出于某种原因,这不会过滤掉相同的框/行/列。应该如何正确编码?

  public int[] getAllowedValues(int row, int col){//both
int[] allowedValues = new int[9];
for(int i = 0; i < 9; i++){
allowedValues[i] = i;
}
for(int i = 0; i < 9; i++){
if(!(board[i][col] == 0)){
allowedValues[board[i][col]] = 0; //anything with a 0 is illegal, with number means that number is legal
}
if(!(board[row][i] == 0)){
allowedValues[board[row][i]] = 0; //anything with a 0 is illegal, with number means that number is legal
}
}
int rowStart = 0; //rowStart is the top left coord of box the number is in
if(row <= 3){
rowStart = 1;
} else if (row <= 6){
rowStart = 4;
} else if (row <= 9){
rowStart = 7;
}
int colStart = 0; //colStart is the top left coord of the box the number is in
if(col <= 3){
colStart = 1;
} else if (col <= 6){
colStart = 4;
} else if (col <= 9){
colStart = 7;
}
for(int i = rowStart; i < rowStart + 3; i++){
for(int j = colStart; j < colStart + 3; j++){
if(!(board[i-1][j-1] == 0)){
allowedValues[board[i-1][j-1]] = 0;
}
}
}
for(int i = row; i < 9; i++){
for(int j = col; j < 9; j++){
if((board[i][j] == 0)){
allowedValues[board[i][j]] = 0;
}
if((board[j][i] == 0)){
allowedValues[board[j][i]] = 0;
}
}
}
return allowedValues;
}

最佳答案

我将向您提供有关如何对此进行编码的步骤。

  1. 导入数组列表

  2. 创建一个值为 1 到 9 的 ArrayList

  3. 对于行、列或 3 x 3 正方形中的每个数字(因此不是允许的值),使用以下代码:

//x is a number in the row/column/square and al is the ArrayList
if(al.contains(x))al.remove(al.indexOf(x));
  1. 将方法类型从int[]改为ArrayList

  2. 返回ArrayList

如果您有任何困难或需要帮助,请告诉我。

关于java - 如何在一定的空间输出有效数字列表?(数独),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004002/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com