Daa Travel Salesman Problem Using Brute Force Method
Daa Travel Salesman Problem Using Brute Force Method
Daa Travel Salesman Problem Using Brute Force Method
21BCE9283 Y.V.K.CHAITANYA
Travel and Salesman Problem
a)Bruteforce Method
CODE:
import java.util.*;
public class TSPBruteForce {
static int[][] graph;
static int numNodes;
static boolean[] visited;
static int minCost = Integer.MAX_VALUE;
static ArrayList<Integer> minPath;
static void tsp(int currentNode, int cost, int count, ArrayList<Integer> path) {
if (count == numNodes && graph[currentNode][0] != 0) {
cost += graph[currentNode][0];
if (cost < minCost) {
minCost = cost;
minPath = new ArrayList<>(path);
}
return;
}
for (int i = 0; i < numNodes; i++) {
if (graph[currentNode][i] != 0 && !visited[i]) {
visited[i] = true;
path.add(i);
tsp(i, cost + graph[currentNode][i], count + 1, path);
visited[i] = false;
path.remove(path.size() - 1);
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of nodes:");
numNodes = scanner.nextInt();
graph = new int[numNodes][numNodes];
System.out.println("Enter the adjacency matrix:");
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
graph[i][j] = scanner.nextInt();
}
}
visited = new boolean[numNodes];
Arrays.fill(visited, false);
visited[0] = true;
ArrayList<Integer> path = new ArrayList<>();
path.add(0);
tsp(0, 0, 1, path);
System.out.println("Minimum Cost: " + minCost);
System.out.println("Path: " + minPath);
scanner.close();
}
}
OUTPUT:
B)Dynamic Programming
CODE:
import java.util.*;
public class TSPDynamicProgramming {
static int[][] graph;
static int numNodes;
static int[][] memo;
static int tsp(int start, int mask) {
if (mask == (1 << numNodes) - 1) {
return graph[start][0];
}
if (memo[start][mask] != -1) {
return memo[start][mask];
}
int minCost = Integer.MAX_VALUE;
for (int next = 0; next < numNodes; next++) {
if ((mask & (1 << next)) == 0 && graph[start][next] != 0) {
int newCost = graph[start][next] + tsp(next, mask | (1 << next));
minCost = Math.min(minCost, newCost);
}
}
return memo[start][mask] = minCost;
}