Hill Climbing算法如何工作?

时间:2017-04-26 12:39:24

标签: c++ artificial-intelligence hill-climbing

我正在从一本书中学习人工智能,这本书模糊地解释了我要在这里发布的代码,我假设因为作者假设每个人都曾经历过攀爬算法。这个概念相当简单,但我只是不明白下面的一些代码,我希望有人在我继续前进之前帮助我更清楚地理解这个算法。

我在最让我困惑的部分旁边评论过,这些行所做的总结对我来说非常有帮助。

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);
}

这本书也没有说明这是什么类型的爬坡。我认为它是基本的爬坡,因为它在卡住时不会重新启动?

1 个答案:

答案 0 :(得分:2)

基本上,它在伪代码中执行此操作:

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)部分只是检查通过交换更改该列表是否会产生较小的长度,如果是,则更新距离,如果不是,则撤消该更改。

我是否涵盖了您想知道的一切?关于特定部分的问题?