/* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ bool SolveSudoku(int grid[N][N]) { int row, col; // If there is no unassigned location, we are done if (!FindUnassignedLocation(grid, row, col)) return true; // success! // consider digits 1 to 9 for (int num = 1; num <= 9; num++) { // if looks promising if (isSafe(grid, row, col, num)) { // make tentative assignment grid[row][col] = num; // return, if success, yay! if (SolveSudoku(grid)) return true; // failure, unmake & try again grid[row][col] = UNASSIGNED; } } return false; // this triggers backtracking }
bool SolveSudoku(int grid[][N]) { int row, col; if (!FindUnassignedLocation(grid, row, col)) { return true; // solved it } for (int num = 1; num <= 9; ++num) { if (IsSafe(grid, row, col, num)) { grid[row][col] = num; if (SolveSudoku(grid)) { return true; } else { grid[row][col] = 0; } } } return false; }
bool SolveSudoku(int grid[N][N]) { int row, col; if (!FindUnassignedLocation(grid, row, col)) return true; for (int num = 1; num <= 9; num++) { if (isSafe(grid, row, col, num)) { grid[row][col] = num; if (SolveSudoku(grid)) return true; grid[row][col] = UNASSIGNED; } } return false; }
int SolveSudoku(int grid[N][N]) { int row, col; if (!FindUnassignedLocation(grid, &row, &col)) return true; long num[N] = {0,0,0,0,0,0,0,0,0}; setCandidates(&num); for (int i = 0; i <= 8; i++) { if (isSafe(grid, row, col, num[i])) { grid[row][col] = num[i]; if (SolveSudoku(grid)) return true; grid[row][col] = UNASSIGNED; } } return false; }
int solveSudoku(int sudoku[MAX_BOUNDS][MAX_BOUNDS]){ int row, col,num; if (!FindUnassignedLocation(sudoku,&row,&col)) return 1; for ( num = 1; num <= 9; num++) { // if looks promising if (isSafe(sudoku, row, col, num)) { // make tentative assignment sudoku[row][col] = num; // return, if success, yay! if (solveSudoku(sudoku)) return 1; // failure, unmake & try again sudoku[row][col] = UNASSIGNED; } } return 0; // this triggers backtracking }