Tuesday, May 27, 2008

A Simple Sudoku Solver in C

Here is a simple Sudoku solver in C. It uses backtracking technique to find all possible solutions.
#include <stdio.h>

/* Display the result. */
void display(const int grid[][9])
{
int i,j;
for (i=0; i<9; i++) {
for (j=0; j<9; j++) {
printf("%d ", grid[i][j]);
}
printf("\n");
}
}

/* Verify the grid is in valid state */
int verify(const int grid[][9], int c, int x, int y)
{
int i, j;
int xs, ys;
for (i=0; i<9; i++) {
if (grid[i][y] == c || grid[x][i] == c)
return 0;
}
xs = x/3;
ys = y/3;
for (i = xs*3; i<(xs+1)*3; i++) {
for (j = ys*3; j< (ys+1)*3; j++) {
if (grid[i][j] == c)
return 0;
}
}
return 1;
}

/* The core of the solver. */
void solve(int grid[][9], int x, int y)
{
if (grid[x][y] != 0) {
if (x==8 && y==8) {
display(grid);
} else {
solve(grid, (x+1)%9, (x==8) ? (y+1) : y);
}
} else {
int c;
for (c=1; c <= 9; c++) {
if (verify(grid, c, x, y)) {
grid[x][y] = c;
solve(grid, x, y);
}
}
grid[x][y] = 0;
}
}

int main()
{
int c[9][9];
int i,j;
for (i=0; i<9; i++) {
for (j=0; j<9; j++) {
scanf("%d ", &(c[i][j]));
}
}
solve(c, 0, 0);
return 0;
}
Compile the program:
cl sudoku.c

Run the program:
sudoku < in.txt

Where in.txt the input file. Here is a sample input file:
(I found it here.)

0 0 1 0 0 5 3 0 0
0 5 0 4 9 0 0 0 0
0 0 0 1 0 2 0 6 4
0 0 0 0 0 0 7 5 0
6 0 0 0 0 0 0 0 1
0 3 5 0 0 0 0 0 0
4 6 0 9 0 3 0 0 0
0 0 0 0 2 4 0 9 0
0 0 3 6 0 0 1 0 0

No comments: