标签:
走迷宫
1 #include<stdio.h> 2 #define MAXSIZE 15 3 char point[MAXSIZE][MAXSIZE]={ 4 {‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘}, 5 {‘ ‘,‘o‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘}, 6 {‘X‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘}, 7 {‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘}, 8 {‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘X‘}, 9 {‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘o‘,‘X‘}, 10 {‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘o‘,‘X‘}, 11 {‘X‘,‘X‘,‘o‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘o‘,‘o‘}, 12 {‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘X‘,‘o‘}, 13 {‘X‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘X‘,‘o‘,‘X‘,‘o‘,‘o‘}, 14 {‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘}, 15 {‘X‘,‘X‘,‘o‘,‘o‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘X‘,‘X‘,‘X‘,‘o‘,‘X‘}, 16 {‘X‘,‘o‘,‘X‘,‘X‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘X‘,‘o‘,‘o‘,‘o‘,‘X‘}, 17 {‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘X‘,‘o‘,‘X‘,‘o‘,‘X‘}, 18 {‘X‘,‘X‘,‘X‘,‘o‘,‘o‘,‘o‘,‘X‘,‘X‘,‘o‘,‘o‘,‘o‘,‘o‘,‘X‘,‘o‘,‘e‘} 19 }; 20 bool visited[MAXSIZE][MAXSIZE]; 21 bool flag = false; //标记是否已经找到了出口 22 23 //遍历迷宫 24 void pathFind(char (*point)[MAXSIZE],int x,int y){ 25 if(!visited[x][y]){ 26 visited[x][y]=true; 27 if(point[x][y]==‘e‘){ 28 point[x][y]=‘ ‘; 29 flag=true; 30 return ; 31 } 32 point[x][y]=‘ ‘; 33 } 34 if((point[x+1][y]==‘o‘||point[x+1][y]==‘e‘)&&visited[x+1][y]!=true&&(x+1<MAXSIZE)){ //向负Y轴 35 pathFind(point,x+1,y); 36 if(flag)//这里的判断很重要,如果不进行判断,则递归的最后一步将会把走过的路径给还原。 37 return ; 38 } 39 if((point[x][y-1]==‘o‘||point[x][y-1]==‘e‘)&&visited[x+1][y-1]!=true&&(y-1>=0)) {//向负x轴 40 pathFind(point,x,y-1); 41 if(flag) 42 return ; 43 } 44 if((point[x-1][y]==‘o‘||point[x-1][y]==‘e‘)&&visited[x-1][y]!=true&&(x-1>=0)) {//向正y轴 45 pathFind(point,x-1,y); 46 if(flag) 47 return ; 48 } 49 if((point[x][y+1]==‘o‘||point[x][y+1]==‘e‘)&&visited[x][y+1]!=true&&(y+1<MAXSIZE)) {//向正x轴 50 pathFind(point,x,y+1); 51 if(flag) 52 return ; 53 } 54 point[x][y]=‘o‘; 55 } 56 /* 57 初始化标记,开始所有的位置都未走过 58 */ 59 void initVisited(bool (*visited)[MAXSIZE]){ 60 for(int i=0;i<MAXSIZE;i++){ 61 for(int j=0;j<MAXSIZE;j++){ 62 visited[i][j]=false; 63 } 64 } 65 } 66 67 /* 68 输出迷宫 69 */ 70 void display(char (*point)[MAXSIZE]){ 71 for(int i=0;i<MAXSIZE;i++){ 72 for(int j=0;j<MAXSIZE;j++){ 73 if(j!=MAXSIZE-1){ 74 printf("%c ",point[i][j]); 75 }else{ 76 printf("%c\n",point[i][j]); 77 } 78 } 79 } 80 } 81 82 int main(){ 83 display(point); 84 initVisited(visited); 85 pathFind(point,1,0); 86 printf("----------------\n"); 87 display(point); 88 89 }
标签:
原文地址:http://www.cnblogs.com/hoojjack/p/4764845.html