-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTSP.java
More file actions
89 lines (88 loc) · 1.48 KB
/
Copy pathTSP.java
File metadata and controls
89 lines (88 loc) · 1.48 KB
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
import java.util.Scanner;
class Nearest
{
int i,j,n,st,sum=0,h=0;
int cost[][]=new int[30][30];
int visited[]=new int[30];
Scanner d=new Scanner(System.in);
void input()
{
System.out.println("Enter the No.of Vertices:");
n=d.nextInt();
System.out.println("Enter the Edge Weight:");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
cost[i][j]=0;
else
{
System.out.print("Edge Weight of Vertices ("+i+","+j+")=");
cost[i][j]=d.nextInt();
if(cost[i][j]==0||cost[i][j]==999)
{
h++;
System.out.println("You Have Entered Incomplete Graph");
break;
}
}
}
if(j!=n+1)
break;
}
if(h==0)
{
System.out.println("Adjacency Matrix::");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
System.out.print(" "+cost[i][j]);
System.out.print("\n");
}
System.out.println("Enter the Source Vertex:");
st=d.nextInt();
}
}
void logic()
{
h=1;
visited[h]=st;
if(st==n)
st=0;
for(i=st+1;i<=n;i++)
{
if(visited[1]==i)
{
sum=sum+cost[visited[h]][i];
visited[++h]=i;
break;
}
else
{
sum=sum+cost[visited[h]][i];
visited[++h]=i;
if(i==n)
i=0;
}
}
}
void out()
{
System.out.println("Path:");
for(i=1;i<=n+1;i++)
System.out.print(visited[i]+" ->");
System.out.print("\n");
System.out.print("Minimum Distance:"+sum);
}
}
class Naandhan
{
public static void main(String []arg)
{
Nearest p=new Nearest();
p.input();
p.logic();
p.out();
}
}