Guest User

nubela

a guest
Sep 21st, 2009
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. package utils;
  2.  
  3. import java.util.LinkedList;
  4.  
  5. public class PuzzleSolverBruteForce {
  6.  
  7. /**
  8. * @param args
  9. */
  10. public static void main(String[] args) {
  11. PuzzleSolverBruteForce test = new PuzzleSolverBruteForce();
  12. int[][] slots = new int[9][9];
  13. int[][] res = test.Solve(slots,true);
  14. }
  15.  
  16. public int[][] Solve(int[][] slots, boolean init) {
  17. if (noEmptySlots(slots))
  18. return slots;
  19. else {
  20. int i = 0, j = 0;
  21. while (i<9) {
  22. j = 0;
  23. while (j<9) {
  24. //check for empty slot.
  25.  
  26. //* if (init==true) System.out.println("BASE: still solving grid " + i + "," + j);
  27. //* else System.out.println("RECURSE: still solving grid " + i + "," + j);
  28. if (slots[i][j] == 0) {
  29. System.out.println("Found current puzzle with empty slot at "+i+":"+j+" , proceeding to get possible values for this empty slot."); //*
  30. //find possible values for empty slot, and fill it in.
  31. PuzzleGenerator value_generator = new PuzzleGenerator();
  32. int[] grid_posi = { i, j };
  33. LinkedList<Integer> possible_values = value_generator
  34. .possibleValuesInGrid(grid_posi, slots);
  35. if (possible_values.size() == 0) {
  36. System.out.println("There are no possible values for this current puzzle, returning false."); //*
  37. slots[0][0] = 0;
  38. return slots;
  39. }
  40. //fill the slot, and check recursively solve it.
  41. System.out.println("We found possible values for this puzzle, they are "+possible_values); //*
  42. for (int x : possible_values) {
  43. System.out.println("Currently looping through this at point "+i+":"+j+", and for this slot, we'll use "+x); //*
  44. int[][] tempslot = slots.clone();
  45. tempslot[i][j] = x;
  46. int[][] possible_sltn = Solve(tempslot,false);
  47. if (noEmptySlots(possible_sltn)) {
  48. System.out.println("We found the right answer!"); //*
  49. return possible_sltn;
  50. }
  51. }
  52. }
  53. j++;
  54. }
  55. i++;
  56. }
  57. }
  58. return slots;
  59. }
  60.  
  61. public boolean noEmptySlots(int[][] slots) {
  62. int i = 0;
  63. while (i < 9) {
  64. int j = 0;
  65. while (j < 9) {
  66. if (slots[i][j] == 0)
  67. return false;
  68. j++;
  69. }
  70. i++;
  71. }
  72. return true;
  73. }
  74.  
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment