///\param puzzle The respective puzzle ///\param file Data file int SolveSudoku(int puzzle[SizeOfPuzzle][SizeOfPuzzle], FILE *fileName){ int row,col; int num; /** If there is no unassigned location, we are done */ if(FindUnassigned(puzzle,&row,&col) == 0 ){ solution++; printf("\t\t Solution no. %d found \n",solution); if(solution < numberOfSolutions){ printPuzzleInFile(fileName, puzzle, SizeOfPuzzle); if(puzzle[0][0] > SizeOfPuzzle){ exit(1); } } else{ printf("\t\t Task solved ! Check solutions file !"); return 1; Sleep(5000); } } iterations = 0; ///\brief Starting counter of iteraions /** Consider digits 1 to SizeOfPuzzle */ for(num = 1;num <= SizeOfPuzzle;num++){ iterations++; if(iterations < 5000){ /** If looks promising */ if(isSafe(puzzle,row,col,num) == 1){ /** Make tentative assignment */ puzzle[row][col] = num; /** Return, if success */ if(SolveSudoku(puzzle, fileName) == 1){ return 1; } /** Failure, unmake & try again */ puzzle[row][col] = UNASSIGNED; } } else{ printf("\t\t No enought iterations for soltion no. %d",solution); fclose(fileName); Sleep(5000); main(); } } return 0; /** This triggers backtracking */ }
bool solve(int grid[N][N]) { int row, col; if(!FindUnassigned(grid, &row, &col)) { return true; } for(int num=1; num<=9; num++) { if(isSafe(grid, row, col, num)) { grid[row][col] = num; if(solve(grid) == true) { return true; } grid[row][col] = 0; // backtrack } } return false; }