aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--c/sudoku.c50
1 files changed, 48 insertions, 2 deletions
diff --git a/c/sudoku.c b/c/sudoku.c
index 040ba8d..072d957 100644
--- a/c/sudoku.c
+++ b/c/sudoku.c
@@ -1,6 +1,44 @@
+#include <stdbool.h>
#include <stdio.h>
+bool inBox(int i, int n, char puzzle[])
+{
+ int boxRow = (i / 9 / 3) * 27;
+ int boxCol = ((i % 9) / 3) * 3;
+
+ for(int j = boxRow; j < boxRow + 27; j += 9) {
+ for(int k = boxCol; k < boxCol + 3; k++){
+ if(puzzle[j + k] - '0' == n)
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool inCol(int i, int n, char puzzle[])
+{
+ int col = i % 9;
+ for(int j = col; j < 81; j += 9) {
+ if(puzzle[j] - '0' == n)
+ return true;
+ }
+ return false;
+}
+
+
+bool inRow(int i, int n, char puzzle[])
+{
+ int row = i/9;
+ for(int j = row; j/9 <= row; j++) {
+ if(puzzle[j] - '0' == n)
+ return true;
+ }
+ return false;
+}
+
+
char* solve(char puzzle[])
{
@@ -11,8 +49,15 @@ char* solve(char puzzle[])
goto next; // this square is answered
}
- // found an unanswered square
- //printf("%d", puzzle[i] - '0');
+ for(int n=1; n<10; n++) {
+ if(inRow(i, n, puzzle) || inCol(i, n, puzzle) || inBox(i, n, puzzle))
+ continue;
+
+ puzzle[i] = n + '0';
+ return solve(puzzle);
+ }
+
+ // need to backtrack
next:
i++;
@@ -41,6 +86,7 @@ void display(char puzzle[])
int main(int argc, char *argv[])
{
+ display(argv[1]);
for(int i=1; i < argc; i++) {
char* puzzle = solve(argv[i]);