Skip to content

Commit b9dca29

Browse files
authored
commit4-travellingsalesman
1 parent 5491ba1 commit b9dca29

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

TravellingSalesman.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import java.util.*;
2+
3+
public class TravellingSalesman
4+
{
5+
private int numberOfNodes;
6+
private Stack<Integer> stack;
7+
8+
public TravellingSalesman()
9+
{
10+
stack = new Stack<Integer>();
11+
}
12+
13+
public void tsp(int adjacencyMatrix[][])
14+
{
15+
numberOfNodes = adjacencyMatrix[1].length - 1;
16+
int[] visited = new int[numberOfNodes];
17+
visited[0] = 1;
18+
stack.push(0);
19+
int element, dst = -1, i;
20+
int min = Integer.MAX_VALUE;
21+
boolean minFlag = false;
22+
System.out.print(0 + "\t");
23+
24+
while (!stack.isEmpty())
25+
{
26+
element = stack.peek();
27+
i = 1;
28+
min = Integer.MAX_VALUE;
29+
while (i <numberOfNodes)
30+
{
31+
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
32+
{
33+
if (min > adjacencyMatrix[element][i])
34+
{
35+
min = adjacencyMatrix[element][i];
36+
dst = i;
37+
minFlag = true;
38+
}
39+
}
40+
i++;
41+
}
42+
if (minFlag)
43+
{
44+
visited[dst] = 1;
45+
stack.push(dst);
46+
System.out.print(dst + "\t");
47+
minFlag = false;
48+
continue;
49+
}
50+
stack.pop();
51+
}
52+
}
53+
54+
public static void main(String... arg)
55+
{
56+
int number_of_nodes;
57+
Scanner scanner = null;
58+
try
59+
{
60+
System.out.println("Enter the number of nodes in the graph");
61+
scanner = new Scanner(System.in);
62+
number_of_nodes = scanner.nextInt();
63+
int adjacency_matrix[][] = new int[number_of_nodes][number_of_nodes];
64+
System.out.println("Enter the adjacency matrix");
65+
for (int i = 0; i < number_of_nodes; i++)
66+
{
67+
for (int j = 0; j < number_of_nodes; j++)
68+
{
69+
adjacency_matrix[i][j] = scanner.nextInt();
70+
}
71+
}
72+
for (int i = 0; i < number_of_nodes; i++)
73+
{
74+
for (int j = 0; j < number_of_nodes; j++)
75+
{
76+
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
77+
{
78+
adjacency_matrix[j][i] = 1;
79+
}
80+
}
81+
}
82+
System.out.println("the citys are visited as follows");
83+
TravellingSalesman obj = new TravellingSalesman();
84+
obj.tsp(adjacency_matrix);
85+
} catch (Exception E)
86+
{
87+
System.out.println(E);
88+
System.out.println("Wrong Input format");
89+
}
90+
scanner.close();
91+
}
92+
}

0 commit comments

Comments
 (0)