在一个MXN的棋盘上,马能够回到起始位置的不同走法,走过的位置不能重复。 算法:回溯法#include <stdio.h> #include <stdlib.h> int row,col,count=0; void horseWalking(int **map,int startx,int starty,int i,int j); void main() { int i,j,startx,starty; printf("Input the number of the row and the number of col:/n"); printf("row:"); scanf("%d",&row); printf("col:"); scanf("%d",&col); int **map=(int**)malloc(sizeof(int*)*row); for(i=0;i<row;i++) { map[i]=(int*)malloc(sizeof(int)*col); } for(i=0;i<row;i++) for(j=0;j<col;j++) { map[i][j]=0; } printf("Input the start position of the horse:/nx:"); scanf("%d",&startx); printf("y:"); scanf("%d",&starty); printf("/n"); horseWalking(map,startx,starty,startx,starty); printf("Total Number:%d/n",count); } void horseWalking(int **map,int startx,int starty,int i,int j) { if(i==startx && j==starty && map[i][j]==1) { count++; return; } if(j-2>=0 && i+1<row &&map[i+1][j-2]==0) { map[i+1][j-2]=1; horseWalking(map,startx,starty,i+1,j-2); map[i+1][j-2]=0; } if(j-1>=0 && i+2<row &&map[i+2][j-1]==0) { map[i+2][j-1]=1; horseWalking(map,startx,starty,i+2,j-1); map[i+2][j-1]=0; } if(j+1<col &&i+2<row &&map[i+2][j+1]==0) { map[i+2][j+1]=1; horseWalking(map,startx,starty,i+2,j+1); map[i+2][j+1]=0; } if(j+2<col && i+1<row &&map[i+1][j+2]==0) { map[i+1][j+2]=1; horseWalking(map,startx,starty,i+1,j+2); map[i+1][j+2]=0; } if(j+2<col && i-1>=0 && map[i-1][j+2]==0) { map[i-1][j+2]=1; horseWalking(map,startx,starty,i-1,j+2); map[i-1][j+2]=0; } if(j+1<col && i-2>=0 && map[i-2][j+1]==0) { map[i-2][j+1]=1; horseWalking(map,startx,starty,i-2,j+1); map[i-2][j+1]=0; } if(j-1>=0 && i-2>=0 && map[i-2][j-1]==0) { map[i-2][j-1]=1; horseWalking(map,startx,starty,i-2,j-1); map[i-2][j-1]=0; } if(j-2<=0 && i-1>=0 && map[i-1][j-2]==0) { map[i-1][j-2]=1; horseWalking(map,startx,starty,i-1,j-2); map[i-1][j-2]=0; } }