forked from clubgamma/Sudoku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.c
95 lines (81 loc) · 2.17 KB
/
sudoku.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
#include <stdio.h>
#include "sudoku.h"
int isValid(Sudoku *s, int row, int col, int num) {
char ch = num + '0';
for (int x = 0; x < SIZE; x++) {
if (s->board[row][x] == ch) {
return 0;
}
}
for (int x = 0; x < SIZE; x++) {
if (s->board[x][col] == ch) {
return 0;
}
}
int startRow = row - row % 3, startCol = col - col % 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (s->board[i + startRow][j + startCol] == ch) {
return 0;
}
}
}
return 1;
}
int findEmpty(Sudoku *s, int *row, int *col) {
for (*row = 0; *row < SIZE; (*row)++) {
for (*col = 0; *col < SIZE; (*col)++) {
if (s->board[*row][*col] == ' ') {
return 1;
}
}
}
return 0;
}
int solveSudoku(Sudoku *s, int *steps) {
int row, col;
if (!findEmpty(s, &row, &col)) {
return 1;
}
for (int num = 1; num <= 9; num++) {
if (isValid(s, row, col, num)) {
s->board[row][col] = num + '0';
(*steps)++;
if (solveSudoku(s, steps)) {
return 1;
}
s->board[row][col] = ' ';
}
}
return 0;
}
void printGrid(Sudoku *s) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
printf("%c ", s->board[row][col]);
if ((col + 1) % 3 == 0 && col < SIZE - 1) {
printf("| ");
}
}
printf("\n");
if ((row + 1) % 3 == 0 && row < SIZE - 1) {
printf("---------------------\n");
}
}
}
int validateInitialBoard(Sudoku *s) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (s->board[row][col] != ' ') {
int num = s->board[row][col] - '0';
s->board[row][col] = ' ';
if (!isValid(s, row, col, num)) {
s->board[row][col] = num + '0';
return 0;
}
s->board[row][col] = num + '0';
}
}
}
return 1;
}