//depot/projects/sudoku/fast/sudoku.c#1 – branch change 149 (text) ·revision history
| 1 | /* |
| 2 | * sudoku.c - backtracking sudoku solver |
| 3 | * |
| 4 | * Because everyone on the SkyTrain is doing these now and I refuse |
| 5 | * to do them by hand. -- ksimpson, may 2005 |
| 6 | * |
| 7 | * usage: sudoku [puzzle.txt] |
| 8 | * puzzle is 9 lines of 9 chars, digits or '.' for blanks |
| 9 | */ |
| 10 | #include <stdio.h> |
| 11 | #include <stdlib.h> |
| 12 | #include <string.h> |
| 13 | |
| 14 | static int grid[9][9]; |
| 15 | static long nodes = 0; |
| 16 | |
| 17 | static int ok(int r, int c, int v) |
| 18 | { |
| 19 | int i, br, bc; |
| 20 | |
| 21 | for (i = 0; i < 9; i++) { |
| 22 | if (grid[r][i] == v || grid[i][c] == v) |
| 23 | return 0; |
| 24 | } |
| 25 | br = (r / 3) * 3; |
| 26 | bc = (c / 3) * 3; |
| 27 | for (i = 0; i < 9; i++) { |
| 28 | if (grid[br + i / 3][bc + i % 3] == v) |
| 29 | return 0; |
| 30 | } |
| 31 | return 1; |
| 32 | } |
| 33 | |
| 34 | static int solve(int pos) |
| 35 | { |
| 36 | int r, c, v; |
| 37 | |
| 38 | if (pos == 81) |
| 39 | return 1; |
| 40 | r = pos / 9; |
| 41 | c = pos % 9; |
| 42 | if (grid[r][c]) |
| 43 | return solve(pos + 1); |
| 44 | for (v = 1; v <= 9; v++) { |
| 45 | nodes++; |
| 46 | if (ok(r, c, v)) { |
| 47 | grid[r][c] = v; |
| 48 | if (solve(pos + 1)) |
| 49 | return 1; |
| 50 | grid[r][c] = 0; |
| 51 | } |
| 52 | } |
| 53 | return 0; |
| 54 | } |
| 55 | |
| 56 | static int read_grid(FILE *f) |
| 57 | { |
| 58 | char line[64]; |
| 59 | int r = 0, c; |
| 60 | |
| 61 | while (r < 9 && fgets(line, sizeof line, f)) { |
| 62 | if (line[0] == '#' || line[0] == '\n') |
| 63 | continue; |
| 64 | for (c = 0; c < 9; c++) |
| 65 | grid[r][c] = (line[c] == '.') ? 0 : line[c] - '0'; |
| 66 | r++; |
| 67 | } |
| 68 | return r == 9; |
| 69 | } |
| 70 | |
| 71 | static void print_grid(void) |
| 72 | { |
| 73 | int r, c; |
| 74 | |
| 75 | for (r = 0; r < 9; r++) { |
| 76 | for (c = 0; c < 9; c++) { |
| 77 | printf("%d", grid[r][c]); |
| 78 | if (c == 2 || c == 5) |
| 79 | printf(" | "); |
| 80 | } |
| 81 | printf("\n"); |
| 82 | if (r == 2 || r == 5) |
| 83 | printf("----+-----+----\n"); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | int main(int argc, char **argv) |
| 88 | { |
| 89 | FILE *f = stdin; |
| 90 | |
| 91 | if (argc > 1 && !(f = fopen(argv[1], "r"))) { |
| 92 | perror(argv[1]); |
| 93 | return 1; |
| 94 | } |
| 95 | if (!read_grid(f)) { |
| 96 | fprintf(stderr, "sudoku: need 9 rows\n"); |
| 97 | return 1; |
| 98 | } |
| 99 | if (!solve(0)) { |
| 100 | printf("no solution (are you sure you copied it right?)\n"); |
| 101 | return 1; |
| 102 | } |
| 103 | print_grid(); |
| 104 | fprintf(stderr, "%ld nodes\n", nodes); |
| 105 | return 0; |
| 106 | } |