This project contains a C program to solve a Sudoku puzzle using a backtracking algorithm. It includes enhancements for printing the board in a specific format and measuring the execution time of the solver.
The algorithm employed is a classic backtracking approach:
- Find Empty Cell: Search for the first empty cell (a cell with a value of
0
) in the Sudoku grid. - Check Validity: For the current empty cell, attempt placing numbers from
1
to9
. For each number, check if placing that number violates the Sudoku rules:- The number must not already be present in the same row.
- The number must not be present in the same column.
- The number must not be present in the 3x3 subgrid that contains the cell.
- Recursive Attempt: If placing the number is valid, place the number and recursively attempt to solve the rest of the grid.
- Backtrack: If placing the number does not lead to a solution (i.e., the recursive call fails), remove the number (reset the cell to
0
) and try the next number. - Solution Found: If all cells are filled correctly, the algorithm terminates, indicating that the solution is found.
- No Solution: If the algorithm exhausts all possibilities and no valid number can be placed, it backtracks. If it backtracks from the first cell, it means no solution exists.
sudoku.c
: The main C program containing the Sudoku solver and timing code.Makefile
: Makefile to compile the C program.job_script.slurm
: SLURM job script to build and run the Sudoku solver.README.txt
: This file.
To compile the Sudoku solver, you can use the provided Makefile. Simply run the following command in your terminal:
make
This will compile the sudoku.c
program and create an executable named sudoku
. You can then run the program using the following command:
./sudoku_solver --board=530070000600195000098000060800060003400803001700020006060000280000419005000080079
The output should look like the following:
Sudoku puzzle:
+-------+-------+-------+
| 5 3 0 | 0 7 0 | 0 0 0 |
| 6 0 0 | 1 9 5 | 0 0 0 |
| 0 9 8 | 0 0 0 | 0 6 0 |
+-------+-------+-------+
| 8 0 0 | 0 6 0 | 0 0 3 |
| 4 0 0 | 8 0 3 | 0 0 1 |
| 7 0 0 | 0 2 0 | 0 0 6 |
+-------+-------+-------+
| 0 6 0 | 0 0 0 | 2 8 0 |
| 0 0 0 | 4 1 9 | 0 0 5 |
| 0 0 0 | 0 8 0 | 0 7 9 |
+-------+-------+-------+
Solved Sudoku puzzle:
+-------+-------+-------+
| 5 3 4 | 6 7 8 | 9 1 2 |
| 6 7 2 | 1 9 5 | 3 4 8 |
| 1 9 8 | 3 4 2 | 5 6 7 |
+-------+-------+-------+
| 8 5 9 | 7 6 1 | 4 2 3 |
| 4 2 6 | 8 5 3 | 7 9 1 |
| 7 1 3 | 9 2 4 | 8 5 6 |
+-------+-------+-------+
| 9 6 1 | 5 3 7 | 2 8 4 |
| 2 8 7 | 4 1 9 | 6 3 5 |
| 3 4 5 | 2 8 6 | 1 7 9 |
+-------+-------+-------+
On a M3 Pro Macbook, the average runtime is 500us; on an Intel(R) Xeon(R) Gold 6226R CPU, this gets reduced to 250us.
Example:
./sudoku_solver --board=530070000600195000098000060800060003400803001700020006060000280000419005000080079