Created
March 29, 2012 05:40
-
-
Save mingyc/2233752 to your computer and use it in GitHub Desktop.
A buggy sudoku solver.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int sudoku[9][9]; | |
int row_count[9][10]; | |
int col_count[9][10]; | |
int box_count[3][3][10]; | |
int check(int r, int c){ | |
if(row_count[r][sudoku[r][c]] != 1) | |
return 0; | |
if(col_count[c][sudoku[r][c]] != 1) | |
return 0; | |
if(box_count[r/3][c/3][sudoku[r][c]] != 1) | |
return 0; | |
return 1; | |
} | |
void set_count(int r, int c){ | |
++row_count[r][sudoku[r][c]]; | |
++col_count[c][sudoku[r][c]]; | |
++box_count[r/3][c/3][sudoku[r][c]]; | |
} | |
void reset_count(int r, int c){ | |
--row_count[r][sudoku[r][c]]; | |
--col_count[c][sudoku[r][c]]; | |
--box_count[r/3][c/3][sudoku[r][c]]; | |
} | |
int solver(int r, int c){ | |
if(r == 9) /* all cells are filled */ | |
return 1; | |
if(sudoku[r][c]){ /* the cell is prefilled */ | |
if(c < 8) return solver(r, c + 1); | |
else return solver(r + 1, 0); | |
} | |
/* try all digits to fill the cell */ | |
for(sudoku[r][c]=1; sudoku[r][c]<=9; ++sudoku[r][c]){ | |
set_count(r, c); | |
if(check(r, c)){ | |
if(c < 8){ | |
if(solver(r, c + 1)) { | |
return 1; | |
} | |
}else{ | |
if(solver(r + 1, 0)) { | |
return 1; | |
} | |
} | |
} | |
reset_count(r, c); | |
} | |
return 0; | |
} | |
int main(){ | |
int r, c; | |
for(r = 0; r < 9; ++r){ | |
for(c = 0; c < 9; ++c){ | |
scanf("%d", &sudoku[r][c]); | |
set_count(r, c); | |
} | |
} | |
if(solver(0, 0)){ | |
for(r = 0; r < 9; ++r){ | |
for(c = 0; c < 8; ++c) | |
printf("%d ", sudoku[r][c]); | |
printf("%d\n", sudoku[r][8]); | |
} | |
}else | |
printf("no solution\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment