我正在用Java的数独求解器工作,在打印输出到数组或网格中时遇到困难。我的算法有效,但是当我运行代码时,它会逐行打印解决方案,而不是网格。 我已经尝试了大部分我知道的尝试将网格和解决方案打印为数组/网格的方法 有什么帮助吗? 会感激
public class Sudoku{
//Grid array
public static int[][] grid = {
{9,0,0,1,0,0,0,0,5},
{0,0,5,0,9,0,2,0,1},
{8,0,0,0,4,0,0,0,0},
{0,0,0,0,8,0,0,0,0},
{0,0,0,7,0,0,0,0,0},
{0,0,0,0,2,6,0,0,9},
{2,0,0,3,0,0,0,0,6},
{0,0,0,2,0,0,9,0,0},
{0,0,1,9,0,4,5,7,0},
};
private int[][] boardGrid;
public static final int EMPTY=0; //empty cell
public static final int SIZE =9;
//Sudoky grid size can be change and update according to the grid
private Sudoku(int [][] boardGrid){
this.boardGrid = new int[SIZE][SIZE];
for (int i=0; i<SIZE; i++){
for(int j=0; j<SIZE; j++){
this.boardGrid[i][j]=boardGrid[i][j];
}
}
}
//checking the grid numbers by row
private boolean isInRow(int row, int number){
for(int i=0; i<SIZE; i++)
if(boardGrid[row][i] == number)
return true;
return false;
}
//checking grid numbers by column
private boolean isInColumn(int col, int number){
for(int i=0; i<SIZE; i++)
if(boardGrid[i][col] == number)
return true;
return false;
}
//checkin if a possible solution is in the 3X2, this can be update to 3X3
private boolean isInBox(int row, int col, int number){
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i<r+3; i++)
for(int j = c; j<c +3; j++)
if(boardGrid[i][j] == number)
return true;
return false;
}
//@method to check for a possivle row and col solution
private boolean isOK(int row, int col, int number){
return !isInRow(row, number) && !isInColumn(col, number) && !isInBox(row, col, number);
}
//Solving method
//
public boolean solve(){
for(int row = 0; row<SIZE; row++){
for(int col = 0; col<SIZE; col++){
//look empty cells
if(boardGrid[row][col] == EMPTY){
//try possible solutions
for(int number = 1; number <= SIZE; number++){
if(isOK(row, col, number)){
//number ok, respecting sudoku restrictions
boardGrid[row][col] = number;
if(solve()){
//looking backtracking
return true;
}
else{
boardGrid[row][col] = EMPTY;
}
}
}
return false;
}
}
}
return true;
}
public void display(){
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++){
System.out.println("" + boardGrid[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args){
Sudoku sudoku = new Sudoku(grid);
System.out.println("Sudoku grid to Solve");
sudoku.display();
//solution
if(sudoku.solve()){
System.out.println("Sudoku Solved");
sudoku.display();
}
else{
System.out.println("No Solution");
}
}
}