private static void solve(Grid grid, List<Grid> solutions) { // Return if there is already more than two solution if (solutions.size() >= 2) { return; } // Find first empty cell int loc = grid.findEmptyCell(); // If no empty cells are found,a solution is found if (loc < 0) { solutions.add(grid.clone()); return; } // Try each of the 9 digits in this empty cell for (int n = 1; n < 10; n++) { if (grid.set(loc, n)) { // With this cell set,work on the next cell solve(grid, solutions); // Clear the cell so that it can be filled with another digit grid.clear(loc); } } }
private int guess() { for (int i = s; i > 0; i--) { for (int j = 0; j < s; j++) { for (int k = 0; k < s; k++) { if (!grid.cellFilled(j, k) && grid.possible(j, k, i)) { grids.push(grid.clone()); guesses.push(new int[] {j, k, i}); // System.out.println("guessing row: "+j+" col: "+k+" is "+i ); // System.out.println(grids.size() + ""); int r = grid.setCellVal(j, k, i); // System.out.println(grid); if (r == 1) { System.out.println("solved"); return 1; } else if (r == -1) { while (r == -1) { if (grids.isEmpty()) { System.out.println("unsolvable"); return -1; } int[] lastGuess = guesses.pop(); // System.out.println("bad guess, removing // possibility of row: " + lastGuess[0] + " col: " + lastGuess[1] + " being " + // lastGuess[2]); // System.out.println(grid); grid = grids.pop(); // System.out.println(grids.size() + ""); r = grid.setCellNot(lastGuess[0], lastGuess[1], lastGuess[2]); } return r; } else { System.out.println("not enough info"); return 0; } } } } } return -1; }
public Solution<Integer> solve() { final Grid<Integer> workingGrid = _initialGrid.clone(); Coord.overGrid(_width, _height) .forEach( from -> from.surroundsWithDiagonals(_width, _height) .forEach(to -> applyConstraint(from, to, workingGrid))); workingGrid.traverse(new ConsolePrintingVisitor<>(System.out)); for (final Group group : _groupByCoord.values()) { for (final Coord from : group.getCoords()) { for (final Coord to : group.getCoords()) { if (!from.equals(to)) { applyConstraint(from, to, workingGrid); } } } } workingGrid.traverse(new ConsolePrintingVisitor<>(System.out)); return new Solution<>(SolutionType.NONE, Optional.<Grid<Integer>>empty()); }