示例#1
0
vector<PuzzleState*> Sudoku::getSuccessors() {
  assert(!isSolution()); // some move remains!

  vector<PuzzleState*> result;

  // find a blank square to fill in
  int row = 0;
  int col = 0;
  for (int i=0; i<9; i++) {
    for (int j=0; j<9; j++) {
      if (grid[i][j]==0) {
	row = i;
	col = j;
	// terminate the loop
	// no labelled breaks :(
	i = 9;
	j = 9;
      }
    }
  }

  for (int digit=1; digit<=9; digit++) {
    if (rowTally[row][digit]) continue; // digit already used in row
    if (colTally[col][digit]) continue; // digit already used in column
    if (zoneTally[row/3][col/3][digit]) continue; // digit already used in zone
    // This is a legal digit!  Add it to possible moves.
    Sudoku *temp = new Sudoku(*this);
    temp->applyMove(row,col,digit);
    result.push_back(temp);
  }

  return result;
}
示例#2
0
bool Sudoku::solve()
{
  if(fin()){
    return true; 
  }
  while(1){
    Move m = findMove();
    if(m.val == 0){
      //no more moves
      return false;
    }
    Sudoku scopy = *this;
    bool result = scopy.applyMove(m);
    if(!result){
      cand[m.ii][m.jj][m.val] = false;
      continue;
    }
    result = scopy.solve();
    if(result){
      *this = scopy;
      return true;
    }else{
      cand[m.ii][m.jj][m.val] = false;
    }
  }
  return false;
}