forked from akshat-o5/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTsp.java
143 lines (56 loc) · 2.61 KB
/
Tsp.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import Java.util.*;
import java.io.*;
import java.util.Scanner;
// create TSPExample class to implement TSP code in Java
class TSPExample
{
// create findHamiltonianCycle() method to get minimum weighted cycle
static int findHamiltonianCycle(int[][] distance, boolean[] visitCity, int currPos, int cities, int count, int cost, int hamiltonianCycle)
{
if (count == cities && distance[currPos][0] > 0)
{
hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]);
return hamiltonianCycle;
}
// BACKTRACKING STEP
for (int i = 0; i < cities; i++)
{
if (visitCity[i] == false && distance[currPos][i] > 0)
{
// Mark as visited
visitCity[i] = true;
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, cities, count + 1, cost + distance[currPos][i], hamiltonianCycle);
// Mark ith node as unvisited
visitCity[i] = false;
}
}
return hamiltonianCycle;
}
// main() method start
public static void main(String[] args)
{
int cities;
//create scanner class object to get input from user
Scanner sc = new Scanner(System.in);
// get total number of cities from the user
System.out.println("Enter total number of cities ");
cities = sc.nextInt();
//get distance of cities from the user
int distance[][] = new int[cities][cities];
for( int i = 0; i < cities; i++){
for( int j = 0; j < cities; j++){
System.out.println("Distance from city"+ (i+1) +" to city"+ (j+1) +": ");
distance[i][j] = sc.nextInt();
}
}
// create an array of type boolean to check if a node has been visited or not
boolean[] visitCity = new boolean[cities];
// by default, we make the first city visited
visitCity[0] = true;
int hamiltonianCycle = Integer.MAX_VALUE;
// call findHamiltonianCycle() method that returns the minimum weight Hamiltonian Cycle
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, 0, cities, 1, 0, hamiltonianCycle);
// print the minimum weighted Hamiltonian Cycle
System.out.println(hamiltonianCycle);
}
}