Java 生成数独网格时出现意外输出
我编写了以下类来生成数独网格。我无法理解该计划的一些结果。有人能解释一下吗Java 生成数独网格时出现意外输出,java,algorithm,sudoku,Java,Algorithm,Sudoku,我编写了以下类来生成数独网格。我无法理解该计划的一些结果。有人能解释一下吗 public class SudokuUtility { static final int max = 8; static final int min = 0; static final int digitMax = 9; static final int digitMin = 0; static final int easyMin = 36; static final
public class SudokuUtility {
static final int max = 8;
static final int min = 0;
static final int digitMax = 9;
static final int digitMin = 0;
static final int easyMin = 36;
static final int easyMax = 49;
static final int mediumMin = 32;
static final int mediumMax = 40;
static final int hardMin = 22;
static final int hardMax = 30;
public static int[][] makeAGrid(String option) {
int[][] grid = new int[9][9];
option = "hard";
Random random = new Random();
int row = 0;
int col = 0;
int randomNumber = 0;
int noOfCellsToBeGenerated = 0;
if ("easy".equals(option)) {
noOfCellsToBeGenerated = random.nextInt((easyMax - easyMin) + 1) + easyMin;
} else if ("medium".equals(option)) {
noOfCellsToBeGenerated = random.nextInt((mediumMax - mediumMin) + 1) + mediumMin;
} else {
noOfCellsToBeGenerated = random.nextInt((hardMax - hardMin) + 1) + hardMin;
}
for (int i = 1; i <= noOfCellsToBeGenerated; i++) {
row = random.nextInt((max - min) + 1) + min;
col = random.nextInt((max - min) + 1) + min;
randomNumber = random.nextInt((digitMax - digitMin) + 1) + digitMin;
if (noConflict(grid, row, col, randomNumber)) {
grid[row][col] = randomNumber;
} else {
i = i - 1; // Nullify this iteration
}
}
int zeroCount = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (grid[i][j] == 0) {
zeroCount++;
}
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
System.out.println("No of zeros in the " + option + " puzzle = " + zeroCount + " and noOfCellsGenerated = " + noOfCellsToBeGenerated);
return grid;
}
public static boolean noConflict(int[][] array, int row, int col, int num) {
for (int i = 0; i < 9; i++) {
if (array[row][i] == num) {
return false;
}
if (array[i][col] == num) {
return false;
}
}
int gridRow = row - (row % 3);
int gridColumn = col - (col % 3);
for (int p = gridRow; p < gridRow + 3; p++) {
for (int q = gridColumn; q < gridColumn + 3; q++) {
if (array[p][q] == num) {
return false;
}
}
}
return true;
}
}
应该有24个生成的数字。实际上有21个。我的逻辑错了吗?但我对逻辑很有把握。我的理解中缺少了什么?我已经在运行您的代码时添加了一些日志记录,这个问题正是我在评论中的意思 如果两次命中同一单元格(行、列),但随机值不同,
noConflict
返回true
,旧值将被覆盖
您应该检查
noConflict
方法中的单元格是否为空。如果您两次点击同一单元格(行、列),该怎么办?我的意思是,如果它已经包含一个数字。@enlait我已经取消了那个迭代。所以它发生了4次,这就解释了区别。@helderdarocha我有一个语句I=I-1;它不是使冲突的位置无效吗?
0 6 0 0 0 1 0 7 0
0 9 0 4 0 0 0 1 0
0 8 0 0 3 0 0 0 0
0 0 0 7 0 0 0 0 0
9 0 0 8 0 0 0 0 0
0 7 0 0 6 0 2 0 0
7 5 0 0 0 0 0 0 9
8 0 0 0 4 0 0 0 0
0 1 0 0 7 0 0 6 0
No of zeros in the hard puzzle = 59 and noOfCellsGenerated = 24