Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package utils;
- import java.util.LinkedList;
- public class PuzzleSolverBruteForce {
- /**
- * @param args
- */
- public static void main(String[] args) {
- PuzzleSolverBruteForce test = new PuzzleSolverBruteForce();
- int[][] slots = new int[9][9];
- int[][] res = test.Solve(slots,true);
- }
- public int[][] Solve(int[][] slots, boolean init) {
- if (noEmptySlots(slots))
- return slots;
- else {
- int i = 0, j = 0;
- while (i<9) {
- j = 0;
- while (j<9) {
- //check for empty slot.
- //* if (init==true) System.out.println("BASE: still solving grid " + i + "," + j);
- //* else System.out.println("RECURSE: still solving grid " + i + "," + j);
- if (slots[i][j] == 0) {
- System.out.println("Found current puzzle with empty slot at "+i+":"+j+" , proceeding to get possible values for this empty slot."); //*
- //find possible values for empty slot, and fill it in.
- PuzzleGenerator value_generator = new PuzzleGenerator();
- int[] grid_posi = { i, j };
- LinkedList<Integer> possible_values = value_generator
- .possibleValuesInGrid(grid_posi, slots);
- if (possible_values.size() == 0) {
- System.out.println("There are no possible values for this current puzzle, returning false."); //*
- slots[0][0] = 0;
- return slots;
- }
- //fill the slot, and check recursively solve it.
- System.out.println("We found possible values for this puzzle, they are "+possible_values); //*
- for (int x : possible_values) {
- System.out.println("Currently looping through this at point "+i+":"+j+", and for this slot, we'll use "+x); //*
- int[][] tempslot = slots.clone();
- tempslot[i][j] = x;
- int[][] possible_sltn = Solve(tempslot,false);
- if (noEmptySlots(possible_sltn)) {
- System.out.println("We found the right answer!"); //*
- return possible_sltn;
- }
- }
- }
- j++;
- }
- i++;
- }
- }
- return slots;
- }
- public boolean noEmptySlots(int[][] slots) {
- int i = 0;
- while (i < 9) {
- int j = 0;
- while (j < 9) {
- if (slots[i][j] == 0)
- return false;
- j++;
- }
- i++;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment