【发布时间】:2012-06-07 15:17:11
【问题描述】:
我目前正在研究 A* 搜索算法。该算法将只是解决文本文件迷宫。我知道 A* 算法应该很快就能找到终点。我的似乎需要 6 秒才能在没有墙壁的 20x20 迷宫中找到路径。它确实以正确的路径找到了终点。
如果我知道代码的哪一部分是问题所在,我会发布它,但我真的不知道出了什么问题。所以这是我使用的算法......
while(!openList.empty()) {
visitedList.push_back(openList[index]);
openList.erase(openList.begin() + index);
if(currentCell->x_coor == goalCell->x_coor && currentCell->y_coor == goalCell->y_coor)
}
FindBestPath(currentCell);
break;
}
if(map[currentCell->x_coor+1][currentCell->y_coor] != wall)
{
openList.push_back(new SearchCell(currentCell->x_coor+1,currentCell->y_coor,currentCell));
}
if(map[currentCell->x_coor-1][currentCell->y_coor] != wall)
{
openList.push_back(new SearchCell(currentCell->x_coor-1,currentCell->y_coor,currentCell));
}
if(map[currentCell->x_coor][currentCell->y_coor+1] != wall)
{
openList.push_back(new SearchCell(currentCell->x_coor,currentCell->y_coor+1,currentCell));
}
if(map[currentCell->x_coor][currentCell->y_coor-1] != wall)
{
openList.push_back(new SearchCell(currentCell->x_coor,currentCell->y_coor-1,currentCell));
}
for(int i=0;i<openList.size();i++) {
openList[i]->G = openList[i]->parent->G + 1;
openList[i]->H = openList[i]->ManHattenDistance(goalCell);
}
float bestF = 999999;
index = -1;
for(int i=0;i<openList.size();i++) {
if(openList[i]->GetF() < bestF) {
for(int n=0;n<visitedList.size();n++) {
if(CheckVisited(openList[i])) {
bestF = openList[i]->GetF();
index = i;
}
}
}
}
if(index >= 0) {
currentCell = openList[index];
}
}
我知道这段代码很乱,而且不是最有效的做事方式,但我认为它应该仍然比原来的更快。任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
我会使用 ctime (cplusplus.com/reference/clibrary/ctime) 之类的东西,并开始计时您正在执行的不同操作,以查找大部分计算时间花费在哪里。有时很难判断算法在哪里花费时间,我发现这是在所有其他方法都失败时找到它的好方法。
-
顺便说一句,我不想吹毛求疵,但距离的正确名称是曼哈顿(就像城市一样,因为它的灵感来自城市街区)。
标签: c++ performance algorithm maze