1

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

我在最让我困惑的部分旁边发表了评论,总结这些行的作用对我很有帮助。

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

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

4

1 回答 1

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 是一个计算两个节点之间距离的助手

if (CurrentDistance < BestDistance)部分只是检查通过交换来更改该列表是否会导致更小的长度,如果是,则更新距离,如果不是,则撤消该更改。

我是否涵盖了您想知道的所有内容?关于特定部分的问题?

于 2017-04-26T13:10:20.840 回答