分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
本文针对数据结构基础系列网络课程(3):栈和队列中第11课时队列的应用-迷宫问题。
例:求出从入口到出口的路径
代码:
#include <stdio.h>#define MaxSize 100#define M 8#define N 8int mg[M+2][N+2]={ {1,1,1,1,1,1,1,1,1,1}, {1,0,0,1,0,0,0,1,0,1}, {1,0,0,1,0,0,0,1,0,1}, {1,0,0,0,0,1,1,0,0,1}, {1,0,1,1,1,0,0,0,0,1}, {1,0,0,0,1,0,0,0,0,1}, {1,0,1,0,0,0,1,0,0,1}, {1,0,1,1,1,0,1,1,0,1}, {1,1,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1}};typedef struct{ int i,j; //方块的位置 int pre; //本路径中上一方块在队列中的下标} Box; //方块类型typedef struct{ Box data[MaxSize]; int front,rear; //队头指针和队尾指针} QuType; //定义顺序队类型void print(QuType qu,int front) //从队列qu中输出路径{ int k=front,j,ns=0; printf("\n"); do //反向找到最短路径,将该路径上的方块的pre成员设置成-1 { j=k; k=qu.data[k].pre; qu.data[j].pre=-1; } while (k!=0); printf("迷宫路径如下:\n"); k=0; while (k<=front) //正向搜索到pre为-1的方块,即构成正向的路径 { if (qu.data[k].pre==-1) { ns++; printf("\t(%d,%d)",qu.data[k].i,qu.data[k].j); if (ns%5==0) printf("\n"); //每输出每5个方块后换一行 } k++; } printf("\n");}int mgpath(int xi,int yi,int xe,int ye) //搜索路径为:(xi,yi)->(xe,ye){ int i,j,find=0,di; QuType qu; //定义顺序队 qu.front=qu.rear=-1; qu.rear++; qu.data[qu.rear].i=xi; qu.data[qu.rear].j=yi; //(xi,yi)进队 qu.data[qu.rear].pre=-1; mg[xi][yi]=-1; //将其赋值-1,以避免回过来重复搜索 while (qu.front!=qu.rear && !find) //队列不为空且未找到路径时循环 { qu.front++; //出队,由于不是环形队列,该出队元素仍在队列中 i=qu.data[qu.front].i; j=qu.data[qu.front].j; if (i==xe && j==ye) //找到了出口,输出路径 { find=1; print(qu,qu.front); //调用print函数输出路径 return(1); //找到一条路径时返回1 } for (di=0; di<4; di++) //循环扫描每个方位,把每个可走的方块插入队列中 { switch(di) { case 0: i=qu.data[qu.front].i-1; j=qu.data[qu.front].j; break; case 1: i=qu.data[qu.front].i; j=qu.data[qu.front].j+1; break; case 2: i=qu.data[qu.front].i+1; j=qu.data[qu.front].j; break; case 3: i=qu.data[qu.front].i, j=qu.data[qu.front].j-1; break; } if (mg[i][j]==0) { qu.rear++; //将该相邻方块插入到队列中 qu.data[qu.rear].i=i; qu.data[qu.rear].j=j; qu.data[qu.rear].pre=qu.front; //指向路径中上一个方块的下标 mg[i][j]=-1; //将其赋值-1,以避免回过来重复搜索 } } } return(0); //未找到一条路径时返回1}int main(){ mgpath(1,1,M,N); return 0;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
给我老师的人工智能教程打call!http://blog.youkuaiyun.com/jiangjunshow
