Skip to content

Instantly share code, notes, and snippets.

@m0r13
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save m0r13/fa8a565c695661015767 to your computer and use it in GitHub Desktop.

Select an option

Save m0r13/fa8a565c695661015767 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int sudoku[9][9];
int read() {
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
scanf("%d", &sudoku[x][y]);
}
}
}
int print() {
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
if (sudoku[x][y])
printf("%d ", sudoku[x][y]);
else
printf(" ");
if (x == 2 || x == 5)
printf("| ");
}
printf("\n");
if (y == 2 || y == 5)
printf("------+-------+------\n");
}
}
int valid(int i, int j) {
for (int x = 0; x < 9; x++)
if (x != i && sudoku[i][j] == sudoku[x][j])
return 0;
for (int y = 0; y < 9; y++)
if (y != j && sudoku[i][j] == sudoku[i][y])
return 0;
int cx = i / 3;
int cy = j / 3;
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if (3*cx+x != i && 3*cy+y != j && sudoku[i][j] == sudoku[3*cx+x][3*cy+y])
return 0;
return 1;
}
int backtrack(int i, int j) {
if (i == 9 && j == 8)
return 1;
if (i == 9)
return backtrack(0, j+1);
for (int n = 1; n <= 9; n++) {
sudoku[i][j] = n;
if (valid(i, j) && backtrack(i+1, j))
return 1;
sudoku[i][j] = 0;
}
return 0;
}
int main() {
read();
print();
printf("\n");
backtrack(0, 0);
print();
}
0 0 4 3 7 0 0 9 2
0 2 8 0 0 1 0 0 7
0 3 5 0 8 0 6 0 1
1 0 2 0 3 0 5 7 8
4 7 0 5 9 8 0 0 3
0 0 0 1 0 0 9 6 4
0 0 9 8 0 6 7 3 5
0 0 7 0 4 3 0 0 6
3 6 0 0 0 2 0 8 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment