[英]Java Sudoku Recursive Solver
我很困惑為什么我仍然遇到這些錯誤。 我在代碼中注釋了導致錯誤的原因。 任何建議都很好。
import java.io.*;
import java.util.*;
public class SudokuSolver {
private static int[][] grid;
int r, c;
public static void main (String [] args) throws FileNotFoundException {
try {
System.out.println("Enter File name: ");
Scanner fin = new Scanner (System.in);
String fname = fin.next();
fin = new Scanner(new FileInputStream(fname));
int [][] board = new int [9][9];
for (int r = 0; r<9; r++) {
for (int c=0; c<9; c++) {
board [r][c] = fin.nextInt();
}
}
for (int r = 0; r < 9; r++) {
for(int c = 0; c < 9; c++) {
System.out.print(board[r][c]);
}
}
if(solveSudoku(grid == true)) //giving an error "Incompatible Operand Types"
printGrid(grid);
else
System.out.printf("No solution exists");
}
catch (FileNotFoundException e){
System.out.println("File could not be found. Exiting...");
System.exit(0);
}
}
public boolean solveSudoku(int[][] grid) {
if(!findUnassignedLocation(grid)) {
return true;
for (int num = 1; num <= 9; num++) {
if(isValid(grid,r,c,digit)) //Throwing error "digit can not be resolved as a variable"
{
grid[r][c] = num;
if(solveSudoku(grid))
return true;
grid[r][c] = 0;
}
return false;
}
}
}
public boolean findUnassignedLocation(int[][] grid) {
for(r = 0; r < 9; r++) {
for(c= 0; c < 9; c++) {
if(grid[r][c]==0)
return false;
}
}
return false;
}
public boolean inRow(int[][] grid, int r, int digit) {
for (int c = 0; c < 9; c++) {
if(grid[r][c] == digit)
return true;
}
return false;
}
public boolean inCol(int[][] grid, int c, int digit) {
for(int r = 0; r < 9; r++ ) {
if(grid[r][c] == digit)
return true;
}
return false;
}
public boolean inBox(int[][] grid, int startR, int startC, int digit) {
for (int r = 0; r <3; r++)
for (int c = 0; c < 3; c++)
if(grid[r+startR][c+startC] == digit)
return true;
return false;
}
public boolean isValid(int[][] grid, int r, int c, int digit) {
return !inRow(grid,r,digit) && !inCol(grid,c,digit) && !inBox(grid,r-r%3,c-c%3,digit);
}
static void printGrid(int[][] grid) {
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
System.out.printf("%2d", grid[row][col]);
System.out.printf("\n");
}
}
}
更改:
if(solveSudoku(grid == true)) //giving an error "Incompatible Operand Types"
if(isValid(grid,r,c,digit)) //Throwing error "digit can not be resolved as a variable"
至:
if(solveSudoku(grid))
if(isValid(grid,r,c,num))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.