FilesSubmittedBranchesLabelsClientsUsersJobsHelp
Tree viewShow file textShow revision historyShow/hide recent activityInformation
Recent activity in //depot/projects/sudoku/main/sudoku.c/...
1562005/06/01ksimpsontreat anything that isn't 1-9 as a blank. puzzles pasted off the newspaper site use '_'
1432005/05/15ksimpsonbox check was using r/3 instead of (r/3)*3. it 'solved' fiendish in 40 nodes. suspicious.
1422005/05/14ksimpsonsudoku solver. everyone on the skytrain is doing these. I refuse to do them by hand.
//depot/projects/sudoku/main/sudoku.c#3

//depot/projects/sudoku/main/sudoku.c#3 – edit change 156 (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
14static int grid[9][9];
15static long nodes = 0;
16
17static 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
34static 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
56static 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 /* anything that isn't 1-9 is a blank: '.', '0', '_', ' ' (job000005) */
65 for (c = 0; c < 9; c++)
66 grid[r][c] = (line[c] >= '1' && line[c] <= '9') ? line[c] - '0' : 0;
67 r++;
68 }
69 return r == 9;
70}
71
72static void print_grid(void)
73{
74 int r, c;
75
76 for (r = 0; r < 9; r++) {
77 for (c = 0; c < 9; c++) {
78 printf("%d", grid[r][c]);
79 if (c == 2 || c == 5)
80 printf(" | ");
81 }
82 printf("\n");
83 if (r == 2 || r == 5)
84 printf("----+-----+----\n");
85 }
86}
87
88int main(int argc, char **argv)
89{
90 FILE *f = stdin;
91
92 if (argc > 1 && !(f = fopen(argv[1], "r"))) {
93 perror(argv[1]);
94 return 1;
95 }
96 if (!read_grid(f)) {
97 fprintf(stderr, "sudoku: need 9 rows\n");
98 return 1;
99 }
100 if (!solve(0)) {
101 printf("no solution (are you sure you copied it right?)\n");
102 return 1;
103 }
104 print_grid();
105 fprintf(stderr, "%ld nodes\n", nodes);
106 return 0;
107}

P4Web/LINUX26X86/2005.1/82295 · Copyright © 1995-2005 Perforce Software · ttul.org