Last active
December 12, 2015 02:08
-
-
Save urielaero/4696228 to your computer and use it in GitHub Desktop.
Sencilla solución de el problema de mover al caballo de ajedrez por las 64 casillas sin repetirlas usando recursividad (backtracking), con arrays dinámicos. (Este código solo imprime una solución)
This file contains hidden or 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> | |
| #include <stdlib.h> | |
| /* | |
| Sencilla solución de el problema de mover al caballo de ajedrez por las | |
| 64 casillas sin repetirlas usando recursividad (backtracking), | |
| con arrays dinámicos. (Este código solo imprime una solución) | |
| */ | |
| void caballo(int i,int j,int **vec,int **puesto); | |
| void limpiar(int **m,unsigned nFil,unsigned nCol); | |
| void imp(int **vec,unsigned nFil,unsigned nCol); | |
| int **CrearMatriz(unsigned nFil,unsigned nCol); | |
| int cont; | |
| int x[8] = {-2,-2,-1,-1,1, 1,2, 2}; | |
| int y[8] = {1, -1,2, -2,-2,2,-1,1}; | |
| int main(){ | |
| int **vec=NULL,**puesto=NULL; | |
| vec=CrearMatriz(64,2); | |
| puesto=CrearMatriz(8,8); | |
| cont=0; | |
| limpiar(vec,64,2); | |
| limpiar(puesto,8,8); | |
| puesto[0][0]=0; | |
| vec[0][0]=0; | |
| vec[0][1]=0; | |
| cont++; | |
| caballo(0,0,vec,puesto); | |
| imp(vec,64,2); | |
| return 0; | |
| } | |
| int **CrearMatriz(unsigned nFil,unsigned nCol){ | |
| int **m=NULL; | |
| int i; | |
| if((m=malloc(sizeof(int*)*nFil))==NULL){ | |
| printf("sin memoria\n"); | |
| return NULL; | |
| } | |
| for(i=0;i<nFil;i++){ | |
| if((m[i]=malloc(sizeof(int)*nCol))==NULL){ | |
| printf("Sin memoria\n"); | |
| } | |
| } | |
| return m; | |
| } | |
| void limpiar(int **m,unsigned nFil,unsigned nCol){ | |
| int i,j; | |
| for(i=0;i<nFil;i++){ | |
| for(j=0;j<nCol;j++){ | |
| m[i][j] = 1; | |
| } | |
| } | |
| } | |
| void caballo(int i,int j,int **vec,int **puesto){ | |
| int t,xt,yt; | |
| for(t=0;t<8;t++){ | |
| xt = i+x[t]; | |
| yt = j+y[t]; | |
| if((xt>=0) && (xt<=7) && (yt>=0) && (yt<=7) && puesto[xt][yt]){ | |
| vec[cont][0] = xt; | |
| vec[cont][1] = yt; | |
| puesto[xt][yt] = 0; | |
| cont++; | |
| caballo(xt,yt,vec,puesto); | |
| if(cont<64){ | |
| puesto[xt][yt] = 1; | |
| cont--; | |
| } | |
| } | |
| } | |
| } | |
| void imp(int **vec,unsigned nFil,unsigned nCol){ | |
| int i,j; | |
| for(i=0;i<nFil;i++){ | |
| for(j=0;j<nCol;j++){ | |
| printf("%d,",vec[i][j]); | |
| } | |
| printf("\n"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment