有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过递归益智显示制作我的数独游戏?

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

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; 
}
}

共 (0) 个答案