我正在从一本书中学习人工智能,这本书含糊地解释了我要在此处发布的代码,我想这是因为作者假设每个人以前都经历过爬山算法。这个概念很简单,但是我只是不理解下面的一些代码,我希望有人在我继续之前可以帮助我更清楚地了解该算法。
我在最让我感到困惑的部分旁评论,这些行的摘要对我很有帮助。
int HillClimb::CalcNodeDist(Node* A, Node* B)
{
int Horizontal = abs(A->_iX - B->_iX);
int Vertical = abs(A->_iY - B->_iY);
return(sqrt(pow(_iHorizontal, 2) + pow(_iVertical, 2)));
}
void HillClimb::StartHillClimb()
{
BestDistance = VisitAllCities();
int CurrentDistance = BestDistance;
while (true)
{
int i = 0;
int temp = VisitAllCities();
while (i < Cities.size())
{
//Swapping the nodes
Node* back = Cities.back();
Cities[Cities.size() - 1] = Cities[i];
Cities[i] = back; // Why swap last city with first?
CurrentDistance = VisitAllCities(); // Why visit all nodes again?
if (CurrentDistance < BestDistance) // What is this doing?
{
BestDistance = CurrentDistance; //???
break;
}
else
{
back = Cities.back();
Cities[Cities.size() - 1] = Cities[i];
Cities[i] = back;
}
i++;
}
if (CurrentDistance == temp)
{
break;
}
}
}
int HillClimb::VisitAllCities()
{
int CurrentDistance = 0;
for (unsigned int i = 0; i < Cities.size(); i++)
{
if (i == Cities.size() - 1)//Check if last city, link back to first city
{
CurrentDistance += CalcNodeDist(Cities[i], Cities[0]);
}
else
{
CurrentDistance += CalcNodeDist(Cities[i], Cities[i + 1]);
}
}
return(CurrentDistance);
}
此外,该书没有说明这是什么类型的爬山。我认为这是基本的爬坡,因为卡住后不会重新启动?
最佳答案
本质上,它使用伪代码执行此操作:
initialize an order of nodes (that is, a list) which represents a circle
do{
find an element in the list so that switching it with the last element of the
list results in a shorter length of the circle that is imposed by that list
}(until no such element could be found)
VisitAllCities是一个计算该圆的长度的助手,CalcNodeDist是一个计算两个节点之间的距离的助手
外部的while循环就是我所说的do-until,内部的while循环遍历所有元素。
if (CurrentDistance < BestDistance)
部分仅检查是否通过交换来更改列表以缩短长度,如果是,请更新距离,否则,请撤消该更改。我是否涵盖了您想知道的所有内容?对特定零件有疑问吗?
关于c++ - 爬山算法如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43634489/