title: How does the Hill Climbing algorithm work?
body: <p>I'm learning Artificial Intelligence from a book, the book vaguely explains the code I'm about to post here, I assume because the author assumes everyone has experienced hill climbing algorithm before. The concept is rather straightforward, but I just don't understand some of the code below and I'd like someone to help me understand this algorithm a bit clearer before I move on.</p>
  
  <p>I commented next to the parts that confuses me most, a summary of what these lines are doing would be very helpful to me.</p>
  
  <pre><code>int HillClimb::CalcNodeDist(Node* A, Node* B)
  {
      int Horizontal = abs(A-&gt;_iX - B-&gt;_iX);
      int Vertical = abs(A-&gt;_iY - B-&gt;_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 &lt; 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 &lt; 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 &lt; 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);
  }
  </code></pre>
  
  <p>Also the book doesn't state what type of hill climb this is. I assume it's basic hill climb as it doesn't restart when it gets stuck? </p>