Guest User

Untitled

a guest
Feb 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class SudokuSolver {
  5. public static void main(String[] args) throws Exception {
  6. // Open the file containing the givens
  7. File file = new File(args[0]);
  8. FileReader rd = new FileReader(args[0]);
  9.  
  10. // Process each grid in the file
  11. while (true) {
  12. Grid grid = Grid.create(rd);
  13. if (grid == null) {
  14. // No more grids
  15. break;
  16. }
  17.  
  18. // Find a solution
  19. List<Grid> solutions = solve(grid);
  20.  
  21. printSolutions(grid, solutions);
  22. }
  23. }
  24.  
  25. // Recursive routine that
  26. private static List<Grid> solve(Grid grid) {
  27. List<Grid> solutions = new ArrayList<Grid>();
  28. solve(grid, solutions);
  29. return solutions;
  30. }
  31.  
  32. private static void solve(Grid grid, List<Grid> solutions) {
  33. // Return if there is already more than two solution
  34. if (solutions.size() >= 2) {
  35. return;
  36. }
  37.  
  38. // Find first empty cell
  39. int loc = grid.findEmptyCell();
  40.  
  41. // If no empty cells are found, a solution is found
  42. if (loc < 0) {
  43. solutions.add(grid.clone());
  44. return;
  45. }
  46.  
  47. // Try each of the 9 digits in this empty cell
  48. for (int n=1; n<10; n++) {
  49. if (grid.set(loc, n)) {
  50. // With this cell set, work on the next cell
  51. solve(grid, solutions);
  52.  
  53. // Clear the cell so that it can be filled with another digit
  54. grid.clear(loc);
  55. }
  56. }
  57. }
  58.  
  59. private static void printSolutions(Grid grid, List<Grid> solutions) {
  60. // Print the grid with the givens
  61. System.out.println("Original");
  62. System.out.println(grid);
  63.  
  64. // Print the solution
  65. if (solutions.size() == 0) {
  66. System.out.println("Unsolveable");
  67. } else if (solutions.size() == 1) {
  68. System.out.println("Solved");
  69. } else {
  70. System.out.println("At least two solutions");
  71. }
  72.  
  73. // Print the solution(s)
  74. for (int i=0; i<solutions.size(); i++) {
  75. System.out.println(solutions.get(i));
  76. }
  77. System.out.println();
  78. System.out.println();
  79. }
  80. }
Add Comment
Please, Sign In to add comment