不多说废话,直接上代码,代码里面有注释,也比较清楚了。
主要是采用了递归,比较初级的思想,代码整体也比较简单,希望我的这一点点东西能帮助到你,能够帮助到你是我莫大的荣幸。
#include#include #include #include #include #include #define N 50 void OutPut(char maze[N][N]); void Init(int array[N][N],char maze[N][N]); int FindWay(char maze[N][N],int array[N][N],int x,int y,int x2,int y2);//输入起点和终点坐标 int array[N][N];//将迷宫数字化,0代表空格,1代表墙 char maze[N][N]= { {'#','#','#','#','#','#','#','#','#','#'}, {'0','0','0','0','0','0','0','0','0','#'}, {'#','0','#','0','#','0','#','#','0','#'}, {'#','0','#','0','#','0','#','#','0','#'}, {'#','0','#','0','#','0','#','#','0','#'}, {'#','0','0','0','0','0','0','0','0','#'}, {'#','#','#','0','#','#','#','0','#','#'}, {'#','#','#','0','0','#','0','0','0','#'}, {'#','#','#','0','#','#','#','0','0','0'}, {'#','#','#','#','#','#','#','#','#','#'}, };//定义迷宫大小,并设置一个10*10的迷宫.用空格表示空气,#表示墙 int main() { int success=0; Init(array,maze); OutPut(maze);//输出之后选择是否出答案 printf("按A出答案,按B退出n"); while(1) { if (_kbhit()) //如果有键盘输入 conio.h里面的函数 { switch (_getch()) { case 'A': case 'a':break;//表示出答案 case'B':case'b':exit(0);//stdlib.h里面的结束函数 break; } break; } } if(FindWay(maze,array,1,0,8,9)==0) { printf("此迷宫无解!!n"); } return 0; } int FindWay(char maze[N][N],int array[N][N],int x,int y,int x2,int y2)//用四个if语句表示四个都要执行 { int temp=0; array[x][y]=8;//设置光标路径 maze[x][y]='@';//小老鼠 system("cls");//清空屏幕 OutPut(maze); array[x][y]=1;//显示完后对走过路径标记 maze[x][y]=' '; Sleep(250);//刷新频率 if(x==x2&&y==y2)//到达终点 { temp=1;//有解 printf("此迷宫的解已输出!!n"); system("PAUSE");//按一下才会结束,给用户良好体验 exit(0); } if(temp!=1&&array[x][y+1]==0&&y+1<=9)//还未找到解,并且右边有路 { FindWay(maze,array,x,y+1,x2,y2); } if(temp!=1&&array[x][y-1]==0&&y-1>=0)//还未找到解,左边有路 { FindWay(maze,array,x,y-1,x2,y2); } if(temp!=1&&array[x-1][y]==0&&x-1>=0)//向下 { FindWay(maze,array,x-1,y,x2,y2); } if(temp!=1&&array[x+1][y]==0&&x+1<=9)//向上 { FindWay(maze,array,x+1,y,x2,y2); } if(temp!=1)//四周无路并且还未找到解,往回退回 { array[x][y]=0; maze[x][y]='#';//此路不通,把它堵住 } return temp; } void Init(int array[N][N],char maze[N][N]) { for(int i=0;i<10;i++)//遍历迷宫 { for(int j=0;j<10;j++) { if(maze[i][j]=='#')//● { array[i][j]=1;//表示墙壁 } else if(maze[i][j]=='0') { array[i][j]==0;//表示有路 } } } } void OutPut(char maze[N][N]) { for(int i=0;i<10;i++) { for(int j=0;j<10;j++) { printf("%2c",maze[i][j]); } printf("n"); } }



