1 #define _CRT_SECURE_NO_WARNINGS 2 #define N 5 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 typedef struct coordinate 7 { 8 int x; 9 int y; 10 }COOR; 11 12 void Show();//打印地图 13 bool Find(COOR s, COOR dir);//寻路 14 15 int map[N][N] = { 16 {1,1,1,1,1}, 17 {1,0,0,0,1}, 18 {1,0,1,0,1}, 19 {1,0,0,0,1}, 20 {1,1,1,1,1}, 21 };//迷宫地图 22 23 24 int main(void) 25 { 26 COOR s = {1,1};//出发地 27 COOR dir = { 3, 3 };//目的地 28 if (Find(s, dir) == 0)//寻路无解 29 { 30 printf("\n该迷宫无解!\n"); 31 } 32 else 33 { 34 printf("\n寻路成功!\n"); 35 Show(); 36 } 37 38 system("pause"); 39 return 0; 40 } 41 42 void Show()//打印地图 43 { 44 int i, j; 45 for (i = 0; i < N; i++) 46 { 47 for (j = 0; j < N; j++) 48 { 49 printf("%d", map[i][j]); 50 } 51 printf("\n"); 52 } 53 } 54 55 bool Find(COOR s, COOR dir)//寻路 56 { 57 int i; 58 if (s.x == dir.x && s.y == dir.y) 59 { 60 printf("(%d,%d)", s.x, s.y); 61 return true; 62 } 63 if (map[s.y][s.x] == 0)//当前路径可行 64 { 65 map[s.y][s.x] = 2;//正确路线 66 67 COOR right = { s.x + 1, s.y };//向右走 68 if (Find(right, dir) == true) 69 { 70 printf("(%d,%d)", s.x, s.y); 71 return true; 72 } 73 74 COOR down = { s.x, s.y + 1 };//向下走 75 if(Find(down, dir) == true) 76 { 77 printf("(%d,%d)", s.x, s.y); 78 return true; 79 } 80 81 COOR left = { s.x - 1, s.y };//向左走 82 if (Find(left, dir) == true) 83 { 84 printf("(%d,%d)", s.x, s.y); 85 return true; 86 } 87 88 COOR up = { s.x, s.y - 1 };//向上走 89 if (Find(up, dir) == true) 90 { 91 printf("(%d,%d)", s.x, s.y); 92 return true; 93 } 94 95 map[s.y][s.x] = 3; 96 return false;//四个方向都不通 97 } 98 return false;//寻路失败 99 }