0

我从下面开始的代码在显示我需要的输出时遇到了问题。有什么地方可以让它显示已解决的代码吗?这是解决 6x6 数独难题的代码,但我似乎无法在解决方法中添加它需要显示的代码。

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class sudoku2{

public static void main(String[] args) throws FileNotFoundException{

int[][] cells = new int[6][6];



readMatrix("puzzle.txt", cells);


System.out.println("Base puzzle:");

displayMatrix(cells);

System.out.println(" ");

solve(0, 0, cells);

 }

public static void displayMatrix(int sudoku[][])throws FileNotFoundException{
for(int i=0; i<6; i++){
 for(int j=0;j<6; j++){  
System.out.print(sudoku[i][j]+" ");  
 }
 System.out.println("");
} 
}

public static void readMatrix(String fileName,int[][] sudoku)throws         FileNotFoundException{
Scanner sc=new Scanner(new FileReader(fileName));

for(int i=0; i<6; i++){

 for(int j=0; j<6; j++){
  sudoku[i][j] = sc.nextInt();
 }
 }
 }
 public static boolean solve(int i, int j, int[][] cells)throws FileNotFoundException {
 if (i == 6) {
    i = 0;
    if (++j == 6)
        return true;
}
if (cells[i][j] != 0)  
    return solve(i+1,j,cells);

for (int val = 1; val <= 6; ++val) {
    if (legal(i,j,val,cells)) {
        cells[i][j] = val;
        if (solve(i+1,j,cells))
            return true;
    }
}
cells[i][j] = 0; 
return false;
}

public static boolean legal(int i, int j, int val, int[][] cells) {
for (int k = 0; k < 6; ++k)  
    if (val == cells[k][j])
        return false;

for (int k = 0; k < 6; ++k) 
    if (val == cells[i][k])
        return false;

int boxRowOffset = (i / 3)*3;
int boxColOffset = (j / 3)*3;
for (int k = 0; k < 3; ++k) 
    for (int m = 0; m < 3; ++m)
        if (val == cells[boxRowOffset+k][boxColOffset+m])
            return false;

return true; 
}
}
4

0 回答 0