电脑鼠走迷宫问题
想请问各位如何才能做到像以下样本程序那样,本人能做到一步一步显示出来罢了。还有写什么代码才能计算每次移动的步速?还有我是用Dev C++这个软件编写的。本人是C语言初学者,恳求解答,谢谢各位。
样本.zip
(8.04 KB)
程序代码:
#include <stdio.h> #include <dos.h> #include <stdlib.h> #define XMAX 10 #define YMAX 10 char maze[XMAX][YMAX] = { "XXXXXXXXXX", "X X X X X", "XX X X X", "XX XXX X", "X X XXX", "XX X X XEX", "X X X X", "XX XXX X X", "XS X X", "XXXXXXXXXX" }; char mazes[XMAX][YMAX] = { "XXXXXXXXXX", "X X X X X", "XX X X X", "XX XXX X", "X X XXX", "XX X X XEX", "X X X X", "XX XXX X X", "XS X X", "XXXXXXXXXX" }; int goAhead(void); int goBack(void); void printMaze(void); void printMazes(void); int mazeWalk(int x, int y); int mazeBack(int x, int y); int main(void){ goAhead(); goBack(); getchar(); return(0); } int goAhead(void){ int x, y, sum; char abc; for (x=0; x<XMAX; x++) for (y=0; y<YMAX; y++) if (maze[x][y]=='S') if(!mazeWalk(x,y)) puts("No route to [E]xit from [S]tart."); printMaze(); printf("\n"); sum=mazeWalk(x,y); printf("\n%d steps are used.\n", &sum); printf("Press Enter to continue for E to S"); scanf("%c", &abc); } int goBack(void){ int x, y; for (x=0; x<XMAX; x++) for (y=0; y<YMAX; y++) if (mazes[x][y]=='E') if(!mazeBack(x,y)) puts("No route to [S]tart from [E]xit."); printMazes(); } void printMaze(void){ int x, y; for (x=0; x<XMAX; x++){ for (y=0; y<YMAX; y++)putchar(maze[x][y]); putchar('\n'); } } void printMazes(void){ int x, y; for (x=0; x<XMAX; x++){ for (y=0; y<YMAX; y++)putchar(mazes[x][y]); putchar('\n'); } } int mazeWalk(int x, int y){ if (maze[x][y]=='E')return(1); if ((maze[x][y+1]==' ')||(maze[x][y+1]=='E')){ maze[x][y]='>'; printMaze(); sleep(1); printf("\n"); if(mazeWalk(x,y+1)) return(1); } if ((maze[x-1][y]==' ')||(maze[x-1][y]=='E')){ maze[x][y]='^'; if(mazeWalk(x-1,y))return(1); } if ((maze[x][y-1]==' ')||(maze[x][y-1]=='E')){ maze[x][y]='<'; if(mazeWalk(x,y-1))return(1); } if ((maze[x+1][y]==' ')||(maze[x+1][y]=='E')){ maze[x][y]='V'; if(mazeWalk(x+1,y))return(1); } maze[x][y]=' '; printMaze(); printf("\n"); sleep(1); return(0); } int mazeBack(int x, int y){ if (mazes[x][y]=='S')return(1); if ((mazes[x][y+1]==' ')||(mazes[x][y+1]=='S')){ mazes[x][y]='>'; printMazes(); sleep(1); printf("\n"); if(mazeBack(x,y+1)) return(1); } if ((mazes[x-1][y]==' ')||(mazes[x-1][y]=='S')){ mazes[x][y]='^'; if(mazeBack(x-1,y))return(1); } if ((mazes[x][y-1]==' ')||(mazes[x][y-1]=='S')){ mazes[x][y]='<'; if(mazeBack(x,y-1))return(1); } if ((mazes[x+1][y]==' ')||(mazes[x+1][y]=='S')){ mazes[x][y]='V'; if(mazeBack(x+1,y))return(1); } mazes[x][y]=' '; printMazes(); printf("\n"); sleep(1); return(0); } /* maze.c : end of code */
[ 本帖最后由 察而斯 于 2014-1-13 22:13 编辑 ]