import java.io.FileNotFoundException; import java.io.IOException; /** * The "main" method for the sudoku solver */ public class Player { public static void main(String[] args) { String[] defaults = { "116m.csv" }; if (args.length == 0) args = defaults; try { GameBoard bg = new GameBoard(args[0]); System.out.println(bg.toStringLegal()); //System.out.println(bg.getLegalMoves()); new Player().solve(bg); //System.out.println(bg.toString()); } catch (FileNotFoundException fnf) { System.err.println(fnf); } catch (IOException ioe) { System.err.println(ioe); } catch (ArrayIndexOutOfBoundsException ai) { System.err.println(ai); } } int rcount = 0; // a count of the number of recursions // because of backtracking this needs to be counted outside the // recursive process public void solve(GameBoard gb) { rcount = 0; GameBoard ngb = solveUtil(gb, 0,0); if (ngb!=null) System.out.println(ngb); System.out.println(rcount); } // the recursive solver!!! public GameBoard solveUtil(GameBoard gb, int xx, int yy) { if (gb.noZeros()) return gb; // solution reached!!!! if (yy>=9) { yy=0; xx++; if (xx>=9) return null; } rcount++; if ((rcount % 1000) == 0) System.out.println(rcount); //System.out.println(this.toString()); if (!gb.solvable()) { //System.out.println(" NOT"); return null; } if (gb.board[xx][yy].value >0) // this position is already occupied, so go on return solveUtil(gb,xx, yy+1); //System.out.println(xx + " " + yy + " " + gb.board[xx][yy]); for (int m=0; m<9; m++) { if (gb.board[xx][yy].legalMoves[m]) { //System.out.println("Trying " + xx + " " + yy + " " + (m+1)); gb.board[xx][yy].value=(m+1); // m+1 because of arrays starting at 0. GameBoard ngb = solveUtil(new GameBoard(gb), xx, yy+1); if (ngb!=null) return ngb; } } return null; } }