/
sudokuSolver.c
501 lines (431 loc) · 15.8 KB
/
sudokuSolver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// -*- compile-command: "gcc -std=c99 -o sudokuSolver sudokuSolver.c -Wall -lm" -*-
// Copyright (c) 2016 Michael Caldwell
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <time.h>
typedef struct puzzle puzzle;
typedef struct coord coord;
struct puzzle {
int cell[9][9][10];
};
struct coord {
int x;
int y;
};
// Check if puzzle is valid.
bool isValidPuzzle(puzzle g, coord *error) {
// Check rows for duplicate values
for (int y=0; y<9; y++)
for (int x=0; x<8; x++)
for (int z=x+1; z<9; z++)
if (g.cell[y][x][0] != 0)
if (g.cell[y][x][0] == g.cell[y][z][0]) {
error->x = z;
error->y = y;
return false;
}
// Check cols for duplicate values
for (int x=0; x<9; x++)
for (int y=0; y<8; y++)
for (int z=y+1; z<9; z++)
if (g.cell[y][x][0] != 0)
if (g.cell[y][x][0] == g.cell[z][x][0]) {
error->x = x;
error->y = z;
return false;
}
// Check quadrants for duplicate values
for (int qx=0; qx<9; qx+=3)
for (int qy=0; qy<9; qy+=3)
{
int used[10] = {0};
for (int y=0; y<3; y++)
for (int x=0; x<3; x++)
{
int cellValue = g.cell[qy+y][qx+x][0];
if (cellValue > 0)
if (++used[cellValue] > 1) {
error->x = qx+x;
error->y = qy+y;
return false;
}
}
}
return true;
}
bool isSolved(puzzle g) {
for (int x=0; x<9; x++)
for (int y=0; y<9; y++)
if (g.cell[x][y][0] == 0)
return false;
return true;
}
void printPuzzle(puzzle g) {
printf("\n");
for (int i=0; i<9; i++)
{
for (int j=0; j<9; j++)
{
// Print number or blank if value is 0
if (g.cell[i][j][0] == 0)
printf(" ");
else
printf(" %d", g.cell[i][j][0]);
// Print vertical separator or newline
if ((j+1) % 3 == 0 && j < 8)
printf(" |");
if (j == 8)
printf("\n");
}
// Print horizontal separator
if ((i + 1) % 3 == 0 && i < 8)
printf("-------+-------+-------\n");
}
printf("\n");
}
void printPuzzleOptions(puzzle g) {
printf("\n");
for (int x=0; x<9; x++)
{
for (int y=0; y<9; y++)
{
if (g.cell[x][y][0] > 0)
printf("%d ", g.cell[x][y][0]);
else
{
printf("[");
for (int i=1; i<10; i++)
if (g.cell[x][y][i] == true)
printf("%d, ", i);
printf("]");
}
}
printf("\n");
}
printf("\n");
}
int isSingleCandidate(puzzle *g, int x, int y) {
int count = 0;
int candidate = 0;
for (int i=1; i<10; i++)
if (g->cell[x][y][i] == false)
count++;
else
candidate = i;
if (count == 8)
return candidate;
return 0;
}
void eliminateNumberInLine(puzzle *g, int x, int y) {
for (int i=0; i<9; i++)
{
if (g->cell[i][y][0] > 0) // Search in row. If not blank (0)...
g->cell[x][y][g->cell[i][y][0]] = false; // Mark candidate for that number as false
if (g->cell[x][i][0] > 0) // Search in col. If not blank (0)...
g->cell[x][y][g->cell[x][i][0]] = false; // Mark candidate for that number as false
}
}
void eliminateNumberInBox(puzzle *g, int x, int y) {
int row = ceil(x/3)*3; // Confine to 3x3 square
int col = ceil(y/3)*3; // Confine to 3x3 square
for (int i=row; i<row+3; i++)
for (int n=col; n<col+3; n++) // Search square
if (g->cell[i][n][0] > 0) // for non-zero values
g->cell[x][y][g->cell[i][n][0]] = false; // Mark false
}
void crossCheckBoxCandidates(puzzle *g, int x, int y) {
int row = ceil(x/3)*3;
int col = ceil(y/3)*3;
for (int j=1; j<10; j++) // For each candidate for x, y
{
if (g->cell[x][y][j] == 0) continue; // Skip non-candidates
bool uniqueCandidate = true;
for (int i=row; i<row+3; i++) // Check if candidates exist in other elements
for (int n=col; n<col+3; n++)
{
if (i==x && n==y) continue; // Don't check self...
if (g->cell[i][n][j] != false) // If candidate exists in other cells
uniqueCandidate = false; // Mark as not unique solution
}
if (uniqueCandidate == true) // If solution is unique...
{
for (int d=1; d<10; d++)
if (d != j)
g->cell[x][y][d] = 0; // Zero out other candidates from x, y
return;
}
}
}
void crossCheckLineCandidates(puzzle *g, int x, int y) {
for (int j=1; j<10; j++) // For each candidate for x, y
{
if (g->cell[x][y][j] == false) continue; // Skip non-candidates
bool uniqueCandidate = true;
for (int i=0; i<9; i++) // Check if candidates exist in row elements
{
if (i == x) continue; // But don't check self...
if (g->cell[i][y][j] != 0) // If candidate is not unique
uniqueCandidate = false; // Mark as not unique
}
if (uniqueCandidate == true) // If solution is unique...
{
for (int d=0; d<9; d++)
if (d != j)
g->cell[x][y][d] = false; // Zero out other candidates from x, y
return;
}
uniqueCandidate = true;
for (int i=0; i<9; i++) // Check if candidates exist in col elements
{
if (i == y) continue; // Don't check self...
if (g->cell[x][i][j] != 0) // If candidate is not unique
uniqueCandidate = false; // Mark as not unique
}
if (uniqueCandidate == true) // If solution is unique...
{
for (int d=1; d<10; d++)
if (d != j)
g->cell[x][y][d] = false; // Zero out other candidates from x, y
return;
}
}
}
void solveGrid(puzzle *g) {
bool changed = true;
while (changed == true)
{
changed = false;
for (int x=0; x<9; x++) // Get candidates & easy solutions
for (int y=0; y<9; y++)
{
if (g->cell[x][y][0] > 0) continue; // Skip non-empty cells
for (int j=1; j<10; j++) g->cell[x][y][j] = true; // Populate candidate values
eliminateNumberInLine(g, x, y); // Eliminate candidates from row & col
eliminateNumberInBox(g, x, y); // Eliminate candidates from box
int newValue = isSingleCandidate(g, x, y); // See if single candidate remains
if (newValue != 0)
{
g->cell[x][y][0] = newValue; // Apply result to cell
changed = true; // Keep track that change was made
}
}
if (changed == true) continue;
for (int x=0; x<9; x++) // Use candidates to find harder solutions
for (int y=0; y<9; y++)
{
if (g->cell[x][y][0] > 0) continue; // Skip non-empty cells
crossCheckLineCandidates(g, x, y); // Check for elements that can only work in current cell
crossCheckBoxCandidates(g, x, y); // Check for elements that can only work in current cell
int newValue = isSingleCandidate(g, x, y); // See if single candidate remains
if (newValue != 0)
{
g->cell[x][y][0] = newValue; // Apply result to cell
changed = true; // Keep track that change was made
}
}
}
}
void guessSolution(puzzle *g, int level) {
if (level > 2) return; // Don't allow recursion beyond 2 to happen.
if (isSolved(*g)) return; // Don't recurse if solved
for (int x=0; x<9; x++)
for (int y=0; y<9; y++)
if (g->cell[x][y][0] == 0) // Look for cells that aren't solved.
{
bool movePossible = false; // Keep track of possible moves
for (int j=1; j<10; j++)
{
puzzle t = *g; // Copy puzzle so we keep original intact
if (t.cell[x][y][j] == true) // See if j is a candidate number
{
movePossible = true; // We have a valid move to try
t.cell[x][y][0] = j; // Set cell to candidate value
solveGrid(&t); // Try solving grid
if (isSolved(t)) // If solved,
{
*g = t; // Copy solved puzzle back to master
return; // and return!
}
else
{
guessSolution(&t, level+1); // Recurse back if not yet solved
if (isSolved(t)) // If that did the trick
{
*g = t; // Copy back to master
return; // And return!
}
}
}
}
if (movePossible == false) // If no valid moves are found
return; // Dead end. Return...
}
}
bool isValidInput(char str[9]) {
// Check for length of string
if (strlen(str) != 9)
return false;
// Make sure all characters are digits
for (int i=0; i<9; i++)
if (str[i] < '0' || str[i] > '9')
return false;
return true;
}
void generateCompleteBoard(puzzle *g) {
srand(time(NULL));
puzzle blank = {};
while(isSolved(*g) == false) {
// Clear puzzle so we can start over
*g = blank;
// Build puzzle by randomly generating every other row
for (int row=0; row < 9;) {
// Populate array with available digits
int available[10] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
for (int i = 0; i<9; i++) {
// Randomly select values for row
int r = 0;
while (available[r] == 0) {
r = rand() % 9 + 1;
}
g->cell[row][i][0] = r;
available[r] = 0;
}
coord tmp = {};
// If randomized row does not invalidate puzzle, advance to next row
if (isValidPuzzle(*g, &tmp)) {
row+=2;
}
}
// Use solving method to fill in remaining squares
solveGrid(g);
if (isSolved(*g) == false)
guessSolution(g, 1);
}
}
void removeSquares(puzzle *g) {
srand(time(NULL));
// 81 squares total
// 75% removal for hard -> ~61
// 55% removal for easy -> ~45
// Number of squares we have to remove from quadrant
int n = rand() % 16 + 45;
int x, y;
// Select the type of symmetry we will have
const int symmetry = rand() % 3;
while (n > 0) {
switch (symmetry) {
// No symmetry
case 0:
// Select random coords
x = rand() % 9;
y = rand() % 9;
// Make sure it's not already blank
if (g->cell[y][x][0] == 0)
continue;
g->cell[y][x][0] = 0;
n--;
break;
// Mirror
case 1:
// Select random coords
x = rand() % 5;
y = rand() % 4;
// Make sure it's not already blank
if (g->cell[y][x][0] == 0)
continue;
g->cell[y][x][0] = 0; // No Flip
g->cell[y][8-x][0] = 0; // Flip Horizontal
g->cell[8-y][x][0] = 0; // Flip Vertical
g->cell[8-y][8-x][0] = 0; // Flip H/V
n -= 4;
// 50/50 for center
if (rand() % 2 == 0 && n-- <= 1)
g->cell[4][4][0] = 0;
break;
// Rotate
case 2:
// Select random coords
x = rand() % 5;
y = rand() % 5;
// Make sure it's not already blank
if (g->cell[y][x][0] == 0)
continue;
g->cell[y][x][0] = 0; // 0 degrees
g->cell[8-y][8-x][0] = 0; // 180 degrees
g->cell[8-x][y][0] = 0; // 90 degrees
g->cell[x][8-y][0] = 0; // 270 degrees
n -= 4;
break;
default:
break;
}
}
}
int main(int argc, char *argv[]) {
// Struct for puzzle
puzzle sudoku = {};
// Parse Arguments
for (int i=1; i<argc; i++)
{
// Generate new puzzle
if (strcmp(argv[i], "-g") == 0)
{
generateCompleteBoard(&sudoku);
removeSquares(&sudoku);
printPuzzle(sudoku);
return(0);
}
}
if (isatty(0))
// Read in game grid
// 0 10 20 30 40 50 60 70 80
// |---------|---------|---------|---------|---------|---------|---------|---------|
printf("Please input each row of the unsolved puzzle without spaces. Enter only 9 \n" \
"digits using 0 to denote unknown values (eg. 100305400).\n\n");
for (int row = 0; row<9; row++)
{
char input[100] = "";
// Verify that puzzle is valid as input so far
retry:
// Get input from the user
if (isatty(0))
printf("Row %d: ", row+1);
scanf("%99s", input);
// Verify 9 digits
if (!isValidInput(input)) {
printf("Invalid input on row %d! Must be 9 digits, and not \"%s\"\n", row+1, input);
if (isatty(0))
goto retry;
exit(1);
}
// Copy input digits to structure
for (int col=0; col<9; col++)
sudoku.cell[row][col][0] = input[col]-'0';
// Verify that new row contains valid puzzle
coord test = {};
if (!isValidPuzzle(sudoku, &test)) {
printf("Puzzle invalidated by value %d (row %d, column %d). Please re-enter row.\n",
*sudoku.cell[test.y][test.x], test.y+1, test.x+1);
if (isatty(0))
goto retry;
exit(1);
}
}
// Print input puzzle
printPuzzle(sudoku);
// Simple deduction first
solveGrid(&sudoku);
// Make some guesses to solve
if (isSolved(sudoku) == false)
guessSolution(&sudoku, 1);
// Print solution
printPuzzle(sudoku);
//if (isSolved(sudoku) == false)
//printf("Unable to solve.");
return 0;
}