0% found this document useful (0 votes)
10 views3 pages

DAA Practical 8

The document provides a brute force solution for the Traveling Salesman Problem using C programming. It includes a code implementation that utilizes an adjacency matrix to calculate the minimum cost of visiting all cities and returning to the starting point. The program prompts the user for the number of cities and the adjacency matrix, then outputs the minimum tour cost.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

DAA Practical 8

The document provides a brute force solution for the Traveling Salesman Problem using C programming. It includes a code implementation that utilizes an adjacency matrix to calculate the minimum cost of visiting all cities and returning to the starting point. The program prompts the user for the number of cities and the adjacency matrix, then outputs the minimum tour cost.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

2CSBS4102-Design And Analysis Of Algorithm

Practical – 8

Q : 8 Implement a brute force solution for the traveling salesman Problem.

Code:

#include <stdio.h>

#include <limits.h>

#define MAX 10 // Maximum number of cities

int graph[MAX][MAX]; // Adjacency matrix

int n; // Number of cities

int visited[MAX]; // Visited array

int minCost = INT_MAX; // Minimum cost found

void tsp(int currentCity, int count, int cost, int startCity) {

if (count == n && graph[currentCity][startCity] > 0) {

// Complete the cycle back to the start city

if (cost + graph[currentCity][startCity] < minCost) {

minCost = cost + graph[currentCity][startCity];

return;

23012571013 U.V Patel College of Engineering Gayatri Solanki


2CSBS4102-Design And Analysis Of Algorithm

for (int i = 0; i < n; i++) {

if (!visited[i] && graph[currentCity][i] > 0) {

visited[i] = 1; // Mark the city as visited

tsp(i, count + 1, cost + graph[currentCity][i], startCity);

visited[i] = 0; // Backtrack

int main() {

printf("Enter the number of cities: ");

scanf("%d", &n);

printf("Enter the adjacency matrix:\n");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

scanf("%d", &graph[i][j]);

for (int i = 0; i < n; i++) visited[i] = 0;

23012571013 U.V Patel College of Engineering Gayatri Solanki


2CSBS4102-Design And Analysis Of Algorithm

visited[0] = 1; // Start from the first city

tsp(0, 1, 0, 0);

printf("The minimum cost of the tour is: %d\n", minCost);

return 0;

Output :

23012571013 U.V Patel College of Engineering Gayatri Solanki

You might also like