Exemplo n.º 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;
  }
Exemplo n.º 2
0
 public void add(String value, int pos) throws Exception {
   Cell tempCell = cells.get(pos);
   tempCell.add(value);
   cells.set(pos, tempCell);
   // and eliminate that value from possibilities of relevant cells
   for (int i = 0; i < 81; i++) {
     if (areRelevant(i, pos)) {
       tempCell = cells.get(i);
       int beforeLength = tempCell.getPossibilities().length();
       tempCell.eliminate(value);
       if (beforeLength > 1 && tempCell.getPossibilities().length() == 1) {
         add(tempCell.getPossibilities(), i);
       }
       cells.set(i, tempCell);
     }
   }
 }