分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
(上接迷宫递归算法)
顺便也把图里求迷宫最短路径算法贴出来,主要思想是利用队列,采用广度优先搜索法,当第一次出现目的点时,中断搜索,并输出路径。程序还是主要使用的C语言,对于队列操作我又重写了下基本操作代码比如入队、出队等,没办法对C++不熟啊!!
个人认为需要说明的是:
1. 为了记录路径,借鉴了树的双亲表示法,所以队列中的数组元素定义如下
typedef
struct
...
{
int location; //(x-1)*3+y
int parent; //记录上一个节点即路径中前驱节点,方便最后输出
} QueueNode;
int location; //(x-1)*3+y
int parent; //记录上一个节点即路径中前驱节点,方便最后输出
} QueueNode;
2.仍然采用了上面的映射思想,公式也是 location=(x-1)*3+y
void
Maze_Shortest(
int
maze[][
5
],point
&
start,point
&
des)
... {
queue Queue;
InitializeQueue(Queue);
EnterQueue(Queue,(start.x-1)*5+start.y,Queue.head);
int direction;
bool FindFlag=false;
int dir[4][2]=...{...{1,0},...{0,1},...{-1,0},...{0,-1}};
while (!EmptyQueue(Queue)&&!FindFlag)
...{
int curX=Queue.array[Queue.head].location/3+1;
int curY=Queue.array[Queue.head].location%3;
for (direction=0;direction<4;direction++) //遍历该点四周四个邻接点
...{
int nextX=curX+dir[direction][0];
int nextY=curY+dir[direction][1];
if (!maze[nextX][nextY]) //如果为0 排除了墙和已经踩过的路
...{
EnterQueue(Queue,(nextX-1)*3+nextY,Queue.head); //入队,入队元素是映射后节点!
if (nextX==des.x&&nextY==des.y)
...{
FindFlag=true;
break;
}
}
}
Queue.head++;
}
if (EmptyQueue(Queue))
...{
printf("找不到路径 ");
}
if(FindFlag)
...{
int pre=Queue.array[--Queue.rear].parent;
Queue.array[1].parent=0;
printf("%d<- ",Queue.array[Queue.rear].location);
while (pre) //迭代输出路径,可惜是逆向输出,不过可以用栈解决
...{
printf("%d<- ",Queue.array[pre].location);
pre=Queue.array[pre].parent;
}
}
... {
queue Queue;
InitializeQueue(Queue);
EnterQueue(Queue,(start.x-1)*5+start.y,Queue.head);
int direction;
bool FindFlag=false;
int dir[4][2]=...{...{1,0},...{0,1},...{-1,0},...{0,-1}};
while (!EmptyQueue(Queue)&&!FindFlag)
...{
int curX=Queue.array[Queue.head].location/3+1;
int curY=Queue.array[Queue.head].location%3;
for (direction=0;direction<4;direction++) //遍历该点四周四个邻接点
...{
int nextX=curX+dir[direction][0];
int nextY=curY+dir[direction][1];
if (!maze[nextX][nextY]) //如果为0 排除了墙和已经踩过的路
...{
EnterQueue(Queue,(nextX-1)*3+nextY,Queue.head); //入队,入队元素是映射后节点!
if (nextX==des.x&&nextY==des.y)
...{
FindFlag=true;
break;
}
}
}
Queue.head++;
}
if (EmptyQueue(Queue))
...{
printf("找不到路径 ");
}
if(FindFlag)
...{
int pre=Queue.array[--Queue.rear].parent;
Queue.array[1].parent=0;
printf("%d<- ",Queue.array[Queue.rear].location);
while (pre) //迭代输出路径,可惜是逆向输出,不过可以用栈解决
...{
printf("%d<- ",Queue.array[pre].location);
pre=Queue.array[pre].parent;
}
}