正文

迷宫搜索2007-06-15 09:14:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/lingdlz/26804.html

分享到:

/************************************************************************\
 迷宫路径搜索的过程显示,编译环境 : TC

 Author  :  Deng Lanzhong / 江南孤峰
 Time    :  07--6--14
 Link me :  Email: lingdlz@163.com qq: 403324669
\************************************************************************/

#include <stdio.h>
#include <graphics.h>
#include <time.h>
#include <setjmp.h>

#define MAZE_X  15   /* 迷宫宽度 */
#define MAZE_Y  10   /* 迷宫高度 */

char    maze[MAZE_Y+2][MAZE_X+2];  /* 定义迷宫 */
int      maze_x_s = (640 - MAZE_X * 20) / 2;   /* 迷宫起始横坐标 */
int      maze_y_s = (480 - MAZE_Y * 20)/2-40;  /* 迷宫起始纵坐标 */
int      search_result = 1;  /* 迷宫搜索结果 */
jmp_buf jumper;   /* 非局部跳转 */

/* 创建随机迷宫 */
void CreateRandMaze(void){
 int i,j;
 for(i = 0; i < MAZE_X+2; i++){
  maze[MAZE_Y+1][i] = maze[0][i] = 1;
  maze[i][0] = maze[i][MAZE_X+1] = 1;
 }
 srand(time(NULL));
 for(i=1; i <= MAZE_Y; i++)
  for(j=1; j <= MAZE_X; j++){
   if(rand()%4)
    maze[i][j] = 0;
   else
    maze[i][j] = 1;
  }
 maze[MAZE_Y][MAZE_X] = 0;
}

/*  初始化界面 */
void InitFace(){
 int i,j,x,y,color;
 setcolor(BLUE);
 x = maze_x_s;
 y = maze_y_s;
 outtextxy(x+10,y-20," MAZE PATH SEARCHING (c) Deng LanZhong");
 outtextxy(x+10,y+50+MAZE_Y*20,"QQ:403324669  Email:lingdlz@163.com");
 setcolor(YELLOW);
 for(i=0; i < MAZE_Y+2; i++)
  for(j=0; j < MAZE_X+2; j++){
   if(maze[i][j])
    setfillstyle(HATCH_FILL, YELLOW);
   else
    setfillstyle(EMPTY_FILL, YELLOW);
   bar(x+j*20,y+i*20,x+20+j*20,y+20+i*20);
  }
}

/* 闲置时间处理 */
void OnIdle(void){
 if(kbhit()){
  if(getch()==27)
   longjmp(jumper,1);
 }
 sleep(1);
}

/* 搜索迷宫路径 */
void SearchPath(int x, int y){
 OnIdle();
 maze[y][x] = 2;
 setfillstyle(SOLID_FILL, RED);
 bar(maze_x_s+x*20,maze_y_s+y*20,maze_x_s+x*20+20,maze_y_s+y*20+20);
 if(x == MAZE_X && y == MAZE_Y){
  search_result = 0;
  longjmp(jumper,1);
 }
 if(!maze[y][x+1])
  SearchPath(x+1,y);
 if(!maze[y+1][x])
  SearchPath(x,y+1);
 if(!maze[y-1][x])
  SearchPath(x,y-1);
 if(!maze[y][x-1])
  SearchPath(x-1,y);
 OnIdle();
 setfillstyle(EMPTY_FILL, YELLOW);
 bar(maze_x_s+x*20,maze_y_s+y*20,maze_x_s+x*20+20,maze_y_s+y*20+20);
}

/*  显示搜索结果 */
void PrintResult(void){
 int x = maze_x_s + 40;
 int y = maze_y_s + MAZE_Y * 20 + 80;
 setcolor(RED);
 if(search_result == 1)
  outtextxy(x,y,"THE MAZE HAVE NO PATH !");
 else
  outtextxy(x,y,"FIND PATH SUCCESS !");
}

int main(void){
 int gdriver=DETECT,gmode,flag;
 
 registerbgidriver(EGAVGA_driver);
 initgraph(&gdriver,&gmode,"d:\\tc");
 
 CreateRandMaze();   /* 创建随机迷宫 */
 InitFace();    /* 初始化界面 */
 flag = setjmp(jumper);
 if(flag == 0)
  SearchPath(1,1);  /* 搜索迷宫路径 */
 PrintResult();
 getch();
 closegraph();
 return 0;
}

阅读(3009) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册