C5老鼠走迷宫问题(二)
在一的基础上遍历出所有路径
只要jerry走到出口,即把一条路径遍历出来
每完成一次完整的模拟即把一条路径显示出来,接着返回上级把他设置为0,即可让这条已显示的路径重新模拟递归
代码如下
1 #include<stdio.h> 2 void walk(int ,int); 3 int jerry[9][9]={{2, 2, 2, 2, 2, 2, 2, 2, 2}, 4 {2, 0, 0, 0, 0, 0, 0, 0, 2}, 5 {2, 0, 2, 2, 0, 2, 2, 0, 2}, 6 {2, 0, 2, 0, 0, 2, 0, 0, 2}, 7 {2, 0, 2, 0, 2, 0, 2, 0, 2}, 8 {2, 0, 0, 0, 0, 0, 2, 0, 2}, 9 {2, 2, 0, 2, 2, 0, 2, 2, 2}, 10 {2, 0, 0, 0, 0, 0, 0, 0, 2}, 11 {2, 2, 2, 2, 2, 2, 2, 2, 2}}; 12 int sti=1,stj=1;//定义入口 13 int endi=7,endj=7;//定义出口 14 int main(){ 15 walk(sti,stj);//调用walk函数 16 return 0; 17 } 18 void walk(int i,int j ){//定义walk函数 19 int m,n; 20 jerry[i][j]=1;//jerry从ij位开始走 21 22 if(i==endi&&j==endj){//即走到出口 ,即遍历一次全部路径 23 for(m=0;m<9;m++){ 24 for(n=0;n<9;n++) 25 { 26 if(jerry[m][n]==2) 27 { 28 printf("A"); 29 } 30 else if(jerry[m][n]==1) 31 { 32 printf("C"); 33 } 34 else 35 printf("B"); 36 } 37 printf("\n"); 38 } 39 printf("\n"); 40 } 41 42 if(jerry[i][j+1]==0)//模拟右移 43 walk(i,j+1); 44 if(jerry[i+1][j]==0)//模拟下移 45 walk(i+1,j); 46 if(jerry[i][j-1]==0)//模拟左移 47 walk(i,j-1); 48 if(jerry[i-1][j]==0)//模拟上移 49 walk(i-1,j); 50 51 jerry[i][j]=0;//退回上一格,重新模拟即可(只有使初值为0,模拟的移动函数才有可能回到初值为0的位置) 52 53 }

浙公网安备 33010602011771号