스도쿠스를 해결하는 프로그램을 작성하려고합니다. 퍼즐을 푸는데 역 추적을 사용하고 있습니다.스도쿠 해결 알고리즘이 예상대로 작동하지 않습니다.
필자가 볼 수있는 한, 제 코드는 작동해야하지만 외관상으로는 그렇지 않습니다. 코드에서 다른 단계의 퍼즐을 보았지만 전혀 변하지 않았습니다. 나는 무엇을해야할지 모른다. 여기에 코드
: 내가 볼 수public class main {
public static int[][] originalGrid;
public static void main(String[] args){
int[][] grid = {{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
originalGrid = grid;
solveSudoku(grid, 0, 0);
System.out.println("Done!");
}
public static boolean solveSudoku(int[][] grid, int row, int col) {
//base case
if (noUnassignedLocation(grid)){
printGrid(grid);
return true;
}
for (int i = 0; i < 9; i++) {
if (noConflict(grid)) {
if (originalGrid[row][col] == 0)
grid[row][col] = i;
printGrid(grid);
col++;
if (col == 9) {
col = 0;
if (row != 8)
row++;
}
if (solveSudoku(grid, row, col))
return true;
grid[row][col] = 0;
col--;
if (col == 0) {
col = 9;
row--;
}
}
}
printGrid(grid);
return false;
}
public static boolean noConflict(int[][] grid) {
for (int i = 0; i < 9; i++) {
for (int j = 0 ; j < 9; j++) {
int current = grid[i][j];
//System.out.println("i: " + i + " j: " + j);
for (int k = 0; k < 9; k++) {
if (current == grid[k][j] && k != i && current != 0 && grid[k][j] != 0) {
return false;
}
}
for (int k = 0; k < 9; k++) {
if (current == grid[i][k] && k != j && current != 0 && grid[i][k] != 0) {
return false;
}
}
//check block
}
}
return true;
}
public static boolean noUnassignedLocation(int[][] grid) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (grid[i][j] == 0) {
return false;
}
}
}
return true;
}
private static void printGrid(int[][] grid) {
System.out.println("###########");
for (int i = 0; i < 9; i++) {
String line = new String();
for (int j = 0; j < 9; j++) {
line = line + grid[i][j];
}
System.out.println("#" + line + "#");
}
System.out.println("###########");
}
}
힌트 : 디버거를 사용하십시오 ... –
와우 나는 그런 존재가 있는지조차 몰랐습니다. 고마워 스티븐 (PS : 냉소적이지 않다) – henne90gen