Exemplo n.º 1
0
void solve(Sudoku input){
  int filledIn=input.getFilledInElements();

  if(filledIn==81){
    input.printGrid();
    cout << endl;
    return;
  }
  for(int i=0; i < 9; i++){
    for(int j=0; j < 9; j++){

      if(input.getCellElement(i,j)==0){

	for(int k=1;k<=9; k++){
	  bool exists=false;
	  for(int l=0;l < 9;l++){
	    if(input.getCellElement(l,j)==k)
	      exists=true;
	  }
	  if(exists==false){
	    for(int l=0;l < 9;l++){
	      if(input.getCellElement(i,l)==k)
		exists=true;
	    }
	  }
	  if(exists==false)
	    if((checkSquareConstraint(input,i,j,k))==true){
	      exists=true;
	    }
	  if(exists==false){
	    Sudoku temp2=new Sudoku(input);
	    temp2.setCellElement(i,j,k);
	    solve(temp2);
	  }
	}
	return;
      }
    }
  }
}
Exemplo n.º 2
0
//Function to check the only-one-number-per-square requirement
bool checkSquareConstraint(Sudoku input,int i,int j,int value){
  int squareindex;
  bool returned=false;

  if(i < 3){
    if(j < 3)
      squareindex=1;
    else if(j < 6)
      squareindex=2;
    else
      squareindex=3;
  }
  else if(i < 6){
    if(j < 3)
      squareindex=4;
    else if(j < 6)
      squareindex=5;
    else
      squareindex=6;
  }
  else{
    if(j < 3)
      squareindex=7;
    else if(j < 6)
      squareindex=8;
    else
      squareindex=9;
  }

  int startk;
  int endk;
  int startl;
  int endl;
  /*The below can be written more compactly, but I thought it was easier 
    to understand this way*/
  if(squareindex==1){
    startk=0;
    endk=3;
    startl=0;
    endl=3;
  }
  else if(squareindex==2){
    startk=0;
    endk=3;
    startl=3;
    endl=6;
  }
  if(squareindex==3){
    startk=0;
    endk=3;
    startl=6;
    endl=9;
  }
  else if(squareindex==4){
    startk=3;
    endk=6;
    startl=0;
    endl=3;
  }
  else if(squareindex==5){
    startk=3;
    endk=6;
    startl=3;
    endl=6;
  }
  else if(squareindex==6){
    startk=3;
    endk=6;
    startl=6;
    endl=9;
  }
  else if(squareindex==7){
    startk=6;
    endk=9;
    startl=0;
    endl=3;
  }
  else if(squareindex==8){
    startk=6;
    endk=9;
    startl=3;
    endl=6;
  }
  else if(squareindex==9){
    startk=6;
    endk=9;
    startl=6;
    endl=9;
  }
  for(int k=startk;k < endk;k++)
    for(int l=startl;l < endl; l++)
      if(input.getCellElement(k,l)==value)
	returned=true;
  
  return returned;
}