“if (n[x][y]=='o')n[x][y]=' '; //这句加得可以吧~”
这句加不得的,只能在完全退出递归后才能还原地图,否则随便给个数据范例就陷入死循环。
这句加不得的,只能在完全退出递归后才能还原地图,否则随便给个数据范例就陷入死循环。
#include<stdio.h>//迷宫路径测试代码 #include<stdlib.h> #define N 11 int COUNT=-1;//计算起点和终点间的步数,如果不存在通向终点的路径,则保留初值-1 typedef struct Node { int x; int y; }Node; Node run[N*N]={0}; void print(char K[][N]) { int i=0; for (i=0;i<N;i++) printf("%s\n",&K[i][0]); } int go(char n [][N],Node run[],int x,int y,int step) { system("cls"); print(n); if (x<0||x>=N||y<0||y>=N) return 0; if (n[x][y]=='E') { COUNT=step; return 1; } if (n[x][y]!=' ') return 0; n[x][y]='o'; run[step].x=x; run[step].y=y; if (go(n,run,x-1,y,step+1)) return 1; if (go(n,run,x+1,y,step+1)) return 1; if (go(n,run,x,y-1,step+1)) return 1; if (go(n,run,x,y+1,step+1)) return 1; if (n[x][y]=='o') n[x][y]=' '; return 0; } int main() { char K[N][N]= { {"**********"}, {"* S* *E*"}, {"* *** ****"}, {"* * * * *"}, {" "}, {"**** "}, {" ******"}, {" "}, {" "}, {" "}, }; int i=0; int j=0; int step=0; for (i=0;i<N;i++) { for (j=0;j<N&&K[i][j]!='S';j++); if (j<N) break; } K[i][j]=' '; if (go(K,run,i,j,step)) printf("Yes\n"); else printf("NO\n"); K[i][j]='S'; // for (i=0;i<N;i++) // for (j=0;j<N;j++) // if (K[i][j]=='o') // K[i][j]=' '; // for (i=0;i<COUNT;i++) // K[run[i].x][run[i].y]='o'; for (i=0;i<N;i++) printf("%s\n",&K[i][0]); printf("The step(s) is: %d\n",COUNT); printf("The Road is:\n"); for (i=0;i<COUNT;i++) { printf("[%d][%d] ",run[i].x,run[i].y); if (i%10==9&&i!=COUNT-1) printf("\n"); } printf("\n"); return 0; }
#include<stdio.h>//注意,迷宫节点不能太多,会影响执行效率 #include<stdlib.h> #include<string.h> #define N 11 int COUNT=-1;//计算起点和终点间的步数,如果不存在通向终点的路径,则保留初值-1 typedef struct Node { int x; int y; }Node; Node run[N*N]={0}; Node run_2[N*N]={0}; void print(char K[][N]) { int i=0; for (i=0;i<N;i++) printf("%s\n",&K[i][0]); } int go(char n [][N],Node run[],int x,int y,int step) { if (x<0||x>=N||y<0||y>=N) return 0; if (n[x][y]=='E'&&(COUNT==-1||step<COUNT)) { int i=0; COUNT=step; for (i=0;i<COUNT;i++) run_2[i]=run[i]; return 0; } else if (n[x][y]=='E') return 0; if (n[x][y]!=' ') return 0; n[x][y]='o'; run[step].x=x; run[step].y=y; if (go(n,run,x-1,y,step+1)) return 1; if (go(n,run,x+1,y,step+1)) return 1; if (go(n,run,x,y-1,step+1)) return 1; if (go(n,run,x,y+1,step+1)) return 1; if (n[x][y]=='o') n[x][y]=' '; return 0; } int main() { char K[N][N]= { {"**********"}, {"* S* *E*"}, {"* *** ** *"}, {"* * * * *"}, {"* *"}, {"*** * ** *"}, {"** * *"}, {"** ** ** *"}, {"* *"}, {"**********"}, }; int i=0; int j=0; int step=0; for (i=0;i<N;i++) { for (j=0;j<N&&K[i][j]!='S';j++); if (j<N) break; } K[i][j]=' '; go(K,run,i,j,step); K[i][j]='S'; for (i=1;i<COUNT;i++) K[run_2[i].x][run_2[i].y]='o'; for (i=0;i<N;i++) printf("%s\n",&K[i][0]); printf("The step(s) is: %d\n",COUNT); printf("The Road is:\n"); for (i=0;i<COUNT;i++) { printf("[%d][%d] ",run_2[i].x,run_2[i].y); if (i%10==9&&i!=COUNT-1) printf("\n"); } printf("\n"); return 0; }
[此贴子已经被作者于2016-12-21 02:17编辑过]
[此贴子已经被作者于2016-12-21 10:31编辑过]