Skip to content

Instantly share code, notes, and snippets.

@GeorgeSeif
Created December 26, 2017 17:26
Show Gist options
  • Save GeorgeSeif/b67f75a039377a29df70a8f1a26c6f8f to your computer and use it in GitHub Desktop.
Save GeorgeSeif/b67f75a039377a29df70a8f1a26c6f8f to your computer and use it in GitHub Desktop.
Brute Force Search algorithm for solving Sudoku
// 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 solve_soduko(int grid[DIM][DIM])
{
// If the Soduko grid has been filled, we are done
if (GRID_FULL == get_unassigned_location(grid))
{
return true;
}
// Get an unassigned Soduko grid location
std::pair<int, int> row_and_col = get_unassigned_location(grid);
int row = row_and_col.first;
int col = row_and_col.second;
// Consider digits 1 to 9
for (int num = 1; num <= 9; num++)
{
// If placing the current number in the current
// unassigned location is valid, go ahead
if (is_safe(grid, row, col, num))
{
// Make tentative assignment
grid[row][col] = num;
// Do the same thing again recursively. If we go
// through all of the recursions, and in the end
// return true, then all of our number placements
// on the Soduko grid are valid and we have fully
// solved it
if (solve_soduko(grid))
{
return true;
}
// As we were not able to validly go through all
// of the recursions, we must have an invalid number
// placement somewhere. Lets go back and try a
// different number for this particular unassigned location
grid[row][col] = BLANK;
}
}
// If we have gone through all possible numbers for the current unassigned
// location, then we probably assigned a bad number early. Lets backtrack
// and try a different number for the previous unassigned locations.
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment