Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Program to Implement Nearest Neighbour Algorithm



In this article, we will see a C++ program to implement the nearest neighbour algorithm: The nearest neighbour algorithm is a greedy algorithm used to find the approximate solution to the Travelling Salesman Problem (TSP) by computing the minimum cost required to visit all the nodes by traversing across the edges only once.

We can implement this algorithm using different data structures like arrays, linked lists, or trees for efficient searching.

How Nearest Neighbour Algorithm Works

  • It start at a given point (eg., a city in TSP).
  • Find the nearest unvisited neighbour based on the distance matrix (eg., uses Ecludean distance).
  • Move to that neighbour and mark it as visited.
  • Repeat the process until all points are visited.
  • Return to the starting point.

Example: Travelling Salesman Problem

This C++ example implements the Travelling Salesman Problem which computes the minimum cost required to visit all the nodes by traversing across the edges only once using the array:

#include<stdio.h>
#include<iostream>
using namespace std;

int c = 0, cost = 999;
int graph[4][4] = {{0, 12, 18, 25 }, {12, 0, 40, 28}, {18, 40, 0, 35}, {25, 28, 35, 0}};

void swap(int * x, int * y) {
   int temp;
   temp = * x;
   * x = * y;
   * y = temp;
}
void copy_array(int * a, int n) {
   int i, sum = 0;
   for (i = 0; i <= n; i++) {
      sum += graph[a[i % 4]][a[(i + 1) % 4]];
   }
   if (cost > sum) {
      cost = sum;
   }
}
void permute(int * a, int i, int n) {
   int j, k;
   if (i == n) {
      copy_array(a, n);
   } else {
      for (j = i; j <= n; j++) {
         swap((a + i), (a + j));
         permute(a, i + 1, n);
         swap((a + i), (a + j));
      }
   }
}
int main() {
   int i, j;
   int a[] = {
      0,
      1,
      2,
      3
   };
   permute(a, 0, 3);
   cout << "minimum cost:" << cost << endl;
}

The above code generates the following output:

minimum cost:93

Travelling Salesman Problem Implementation Using Linked List

This is another C++ program to implement TSP using the nearest neighbour algorithm through the linked list:

#include <iostream>
#include <limits.h>
using namespace std;

struct Node {
   int city;
   int distance;
   Node * next;
};

class LinkedList {
   public: Node * head;

   LinkedList() {
      head = nullptr;
   }

   void insert(int city, int distance) {
      Node * newNode = new Node();
      newNode -> city = city;
      newNode -> distance = distance;
      newNode -> next = nullptr;

      if (!head) {
         head = newNode;
      } else {
         Node * temp = head;
         while (temp -> next) {
            temp = temp -> next;
         }
         temp -> next = newNode;
      }
   }

   void display() {
      Node * temp = head;
      while (temp) {
         cout << temp -> city << " -> ";
         temp = temp -> next;
      }
      cout << "End\n";
   }
};

#define N 4
int graph[4][4] = {{0, 12, 18, 25 }, {12, 0, 40, 28}, {18, 40, 0, 35}, {25, 28, 35, 0}};

void nearestNeighbor(int start) {
   LinkedList path;
   bool visited[N] = {
      false
   };
   int current = start, totalCost = 0;

   path.insert(current, 0);
   visited[current] = true;

   for (int i = 0; i < N - 1; i++) {
      int nearest = -1, minDist = INT_MAX;

      for (int j = 0; j < N; j++) {
         if (!visited[j] && graph[current][j] < minDist) {
            nearest = j;
            minDist = graph[current][j];
         }
      }

      visited[nearest] = true;
      totalCost += minDist;
      path.insert(nearest, minDist);
      current = nearest;
   }

   totalCost += graph[current][start]; // Returning to start
   path.insert(start, graph[current][start]);

   cout << "Path followed: ";
   path.display();
   cout << "Total Cost: " << totalCost << endl;
}

int main() {
   int startCity = 0;
   nearestNeighbor(startCity);
   return 0;
}

Cost Of the nearest path to reach destination:

Path followed: 0 -> 1 -> 3 -> 2 -> 0 -> End
Total Cost: 93
Updated on: 2025-05-21T14:25:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements