-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathTravellingSalesman.java
62 lines (38 loc) · 1.42 KB
/
TravellingSalesman.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package Algorithms;
public class TravellingSalesman
{
static int tsp(int[][] graph, boolean[] v,
int currPos, int n,
int count, int cost, int ans)
{
if (count == n && graph[currPos][0] > 0)
{
ans = Math.min(ans, cost + graph[currPos][0]);
return ans;
}
for (int i = 0; i < n; i++)
{
if (v[i] == false && graph[currPos][i] > 0)
{
v[i] = true;
ans = tsp(graph, v, i, n, count + 1,
cost + graph[currPos][i], ans);
v[i] = false;
}
}
return ans;
}
public static void main(String[] args)
{
int n = 4;
int[][] graph = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
boolean[] v = new boolean[n];
v[0] = true;
int ans = Integer.MAX_VALUE;
ans = tsp(graph, v, 0, n, 1, 0, ans);
System.out.println(ans);
}
}