バックトラックに基づく数独解決アルゴリズムを実装する方法について、私は何時間もかけて考えてきました。ただし、問題が発生しました。エラーが発生すると、アルゴリズムはバックトラックしません。物事をできるだけ単純にするために、これが私の主な機能です。
public class Sudoku {
private int[][] grid = new int[9][9];
private int col;
private int row;
public boolean solveSudoku() {
if(!(this.FindEmptyCell())) {
return true;
}
for(int num = 1; num <= 9; num++) {
if(this.isPossible(this.col, this.row, num)) {
this.grid[this.col][this.row] = num;
if(this.solveSudoku()) {
return true;
}
this.grid[col][row] = 0;
}
}
return false;
}
}
Sudoku クラスのコンストラクターは空のボードを作成し、コンピューターは Sudoku のルールを満たす数字でグリッド全体を埋める必要があります。
FindEmptyCell メソッドは、行フィールドと列フィールドの値を、最初の空いているセルのインデックスと等しくなるように設定します。このグリッドは、プログラムが false を返したときの状態を表しています。
1 2 3 4 5 6 7 8 9
4 5 6 1 2 3 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
この時点までのすべてが私のアルゴリズムで正しいかどうか教えてください。もしそうなら、それはエラーが補助機能のどこかにあることを意味します。たとえば、フィールドを使用してインデックスを格納してもバックトラッキングが防止されないかどうかはわかりません。
どんな助けでも大歓迎です。また、この投稿がこの掲示板のルールにある程度違反している場合は、反対票を投じる前にコメントでお知らせください。今後はこのような間違いを避けたいと考えています。
編集:残りの方法を提供:
public Sudoku() {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
grid[i][j] = 0;
}
}
}
public boolean FindEmptyCell(int col, int row) {
for(col = 0; col < 9; col++) {
for(row = 0; row < 9; row++) {
if(this.grid[col][row] == 0) {
return true;
}
}
}
return false;
}
public boolean usedInRow(int row, int num) {
for(int col = 0; col < 9; col++) {
if(grid[col][this.row] == num) {
return true;
}
}
return false;
}
public boolean usedInColumn(int col, int num) {
for(int row = 0; row < 9; row++) {
if(grid[this.col][row] == num) {
return true;
}
}
return false;
}
public boolean usedInBox(int boxStartRow, int boxStartCol, int num) {
for(int col = 0; col < 3; col++) {
for(int row = 0; row < 3; row++) {
if(grid[col+boxStartCol][row + boxStartRow] == num) {
return true;
}
}
}
return false;
}
public boolean isPossible(int col, int row, int number) {
return !(this.usedInRow(this.row, number)) && !this.usedInColumn(this.col, number) && !this.usedInBox(row - row%3, col-col%3, number);
}