Last active
July 26, 2022 04:55
-
-
Save asubramanian08/92aa00f852f6475dae99b6d6c856af3c to your computer and use it in GitHub Desktop.
Solve any sudoku board through a brute force filling algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <utility> | |
using namespace std; | |
// Arrays and macros | |
#define SIDE_LEN 9 | |
bool rows[SIDE_LEN][SIDE_LEN] = {false}; | |
bool cols[SIDE_LEN][SIDE_LEN] = {false}; | |
bool boxes[SIDE_LEN][SIDE_LEN] = {false}; | |
#define BLANK 0 | |
int grid[SIDE_LEN][SIDE_LEN]; | |
#define BOX(row, col) ((row / 3) * 3 + (col / 3)) | |
// functions | |
bool recursiveFill(int row, int col); | |
bool callNext(int row, int col) | |
{ | |
col = (col + 1) % SIDE_LEN; | |
row = row + (col == 0); | |
return recursiveFill(row, col); | |
} | |
bool recursiveFill(int row, int col) | |
{ | |
if (row == SIDE_LEN) | |
return true; | |
if (grid[row][col] != BLANK) | |
return callNext(row, col); | |
for (int i = 0; i < SIDE_LEN; i++) | |
if (!rows[i][row] && !cols[i][col] && !boxes[i][BOX(row, col)]) | |
{ | |
rows[i][row] = cols[i][col] = boxes[i][BOX(row, col)] = true; | |
grid[row][col] = i + 1; | |
if (callNext(row, col)) | |
return true; | |
rows[i][row] = cols[i][col] = boxes[i][BOX(row, col)] = false; | |
} | |
grid[row][col] = BLANK; | |
return false; | |
} | |
int main(void) | |
{ | |
// read given board | |
cout << "Enter the board, use " << BLANK << " for a blank tile:" << endl; | |
for (int i = 0; i < SIDE_LEN; i++) | |
for (int j = 0; j < SIDE_LEN; j++) | |
{ | |
int number; | |
cin >> number; | |
grid[i][j] = number; | |
if (number == BLANK) | |
continue; | |
rows[number - 1][i] = cols[number - 1][j] = | |
boxes[number - 1][BOX(i, j)] = true; | |
} | |
cout << endl; | |
// fill tiles -> print solution | |
recursiveFill(0, 0); | |
cout << "Solution board:" << endl; | |
for (int i = 0; i < SIDE_LEN; i++) | |
{ | |
for (int j = 0; j < SIDE_LEN; j++) | |
cout << grid[i][j] << ' '; | |
cout << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment