Example #1
0
  public ArrayList<String> solve() {

    // save base/original puzzle
    savePuzzle(0, 0);
    Boolean succeeded = false;

    outerloop:
    for (int i = 0; i < 81; i++) { // for each cell in the puzzle

      if (cells.get(i).getPossibilities().length() > 1) {
        succeeded = false;

        while (trialPos < cells.get(i).getPossibilities().length()) {
          String trialValue = String.valueOf(cells.get(i).getPossibilities().charAt(trialPos));

          try {
            add(trialValue, i);
            if (solved()) {
              break outerloop;
            } else { // Value was successfully added (didn't break try)
              succeeded = true;
              // System.out.println("Succeeded with " + trialValue + " at cell " + i + " trialPos =
              // " + trialPos);
              savePuzzle(i, trialPos + 1);
              trialPos = 0;
              break;
            }
          } catch (Exception e) {
            // Value was NOT successfully added. Reset puzzle and try next value.
            // System.out.println("Failed with " + trialValue + " at cell " + i + " trialPos = " +
            // trialPos);
            resetPuzzle();
          }

          trialPos++;
        }

      } else if (cells.get(i).getPossibilities().length() == 1) {
        succeeded = true;
        // System.out.println("One possible value at cell " + i);
        trialPos = 0;
      }

      if (succeeded == false) {
        // no value worked. Backtrack.
        // System.out.println("*****FAILED, GO BACK*****");
        i = goBack();
      }
    }

    ArrayList<String> result = new ArrayList<>();
    for (Cell c : cells) {
      result.add(c.getPossibilities());
    }

    return result;
  }