Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define M 9
- /*
- *
- */
- int get_next_position(int sudoku[M][M], int* f, int* c){
- int i,j;
- for ( i=0;i<M;i++){
- for (j=0;j<M;j++){
- if (sudoku[i][j]==0){
- *f=i;*c=j;
- return 1;
- }
- }
- }
- return 0;
- }
- void pprint(int sudoku[M][M]){
- int i,j;
- for (i=0;i<M;i++){
- for (j=0;j<M;j++){
- printf("%d ",sudoku[i][j]);
- }
- printf("\n");
- }
- }
- int numvalido(int sudoku[M][M],int f,int c,int num){
- //filas y columnas
- int i,j;
- for (i=0;i<M;i++){
- if(sudoku[i][c]==num)
- return 0;
- if(sudoku[f][i]==num)
- return 0;
- }
- int i_cuad = (f/3)*3; // OJO: Es división entera porque los operandos son enteros
- int j_cuad = (c/3)*3; // OJO: Es división entera porque los operandos son enteros
- for (i = 0; i < 3; i++)
- for (j = 0; j < 3; j++)
- if (sudoku[i+i_cuad][j+j_cuad] == num)
- return 0;
- //cuadrados
- /*int f_cuad = (f+3)/3;
- int c_cuad = (c+3)/3;
- for (i = 0; i < 3; i++)
- for (j = 0; j < 3; j++)
- if (sudoku[i+(f_cuad-1)*3][j+(c_cuad-1)*3] == num)
- return 0;*/
- return 1;
- }
- int solve_sudoku(int sudoku[M][M]){
- int f, c,num;
- /* Caso Base: No hay posiciones disponibles*/
- if (!get_next_position(sudoku, &f, &c))
- return 1;
- for(num=1;num<M+1;num++){
- if(numvalido(sudoku,f,c,num)){
- sudoku[f][c]=num;
- if(solve_sudoku(sudoku))
- return 1;
- sudoku[f][c]=0;
- }
- }
- return 0;
- }
- int main() {
- int sudoku[M][M] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
- {5, 2, 0, 0, 0, 0, 0, 0, 0},
- {0, 8, 7, 0, 0, 0, 0, 3, 1},
- {0, 0, 3, 0, 1, 0, 0, 8, 0},
- {9, 0, 0, 8, 6, 3, 0, 0, 5},
- {0, 5, 0, 0, 9, 0, 6, 0, 0},
- {1, 3, 0, 0, 0, 0, 2, 5, 0},
- {0, 0, 0, 0, 0, 0, 0, 7, 4},
- {0, 0, 5, 2, 0, 6, 3, 0, 0}};
- if (solve_sudoku(sudoku))
- pprint(sudoku);
- else
- printf("No existe solución");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment