Skip to content

Commit cf9a5a1

Browse files
authored
Create Travelling Salesman Problem.java
1 parent 535f463 commit cf9a5a1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Travelling Salesman Problem.java

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Java implementation of the approach
2+
class GFG
3+
{
4+
5+
// Function to find the minimum weight
6+
// Hamiltonian Cycle
7+
static int tsp(int[][] graph, boolean[] v,
8+
int currPos, int n,
9+
int count, int cost, int ans)
10+
{
11+
12+
// If last node is reached and it has a link
13+
// to the starting node i.e the source then
14+
// keep the minimum value out of the total cost
15+
// of traversal and "ans"
16+
// Finally return to check for more possible values
17+
if (count == n && graph[currPos][0] > 0)
18+
{
19+
ans = Math.min(ans, cost + graph[currPos][0]);
20+
return ans;
21+
}
22+
23+
// BACKTRACKING STEP
24+
// Loop to traverse the adjacency list
25+
// of currPos node and increasing the count
26+
// by 1 and cost by graph[currPos,i] value
27+
for (int i = 0; i < n; i++)
28+
{
29+
if (v[i] == false && graph[currPos][i] > 0)
30+
{
31+
32+
// Mark as visited
33+
v[i] = true;
34+
ans = tsp(graph, v, i, n, count + 1,
35+
cost + graph[currPos][i], ans);
36+
37+
// Mark ith node as unvisited
38+
v[i] = false;
39+
}
40+
}
41+
return ans;
42+
}
43+
44+
// Driver code
45+
public static void main(String[] args)
46+
{
47+
48+
// n is the number of nodes i.e. V
49+
int n = 4;
50+
51+
int[][] graph = {{0, 10, 15, 20},
52+
{10, 0, 35, 25},
53+
{15, 35, 0, 30},
54+
{20, 25, 30, 0}};
55+
56+
// Boolean array to check if a node
57+
// has been visited or not
58+
boolean[] v = new boolean[n];
59+
60+
// Mark 0th node as visited
61+
v[0] = true;
62+
int ans = Integer.MAX_VALUE;
63+
64+
// Find the minimum weight Hamiltonian Cycle
65+
ans = tsp(graph, v, 0, n, 1, 0, ans);
66+
67+
// ans is the minimum weight Hamiltonian Cycle
68+
System.out.println(ans);
69+
}
70+
}
71+
72+
// This code is contributed by Raj Chakraborty

0 commit comments

Comments
 (0)