forked from ronijpandey/Java-Codes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebGraph.java
175 lines (121 loc) · 3.62 KB
/
WebGraph.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package javacodes;
/**
* This class is to represent a Graph and to perform some operation in Graph
*/
import java.util.*;
class WebGraph
{
private int V;
private LinkedList<Integer> adj[];
private int dist[];
private int par[];
/**
* Constructor to create a WebGraph
* @param v
*/
WebGraph(int v)
{
V = v;
adj = new LinkedList[v];
dist=new int[v];
par=new int[v];
for (int i=0; i<v; ++i)
{adj[i] = new LinkedList();
}
}
/**
* This is to add an edge in the WebGraph with Vertices v and Weight w
* @param v
* @param w
*/
void addEdge(int v,int w)
{
adj[v].add(w);
}
/**
* This api performs Breadth First Search in (this)WebGraph
* @param s
*/
void BFS(int s)
{
boolean visited[] = new boolean[V];
for(int i=0;i<V;i++)
{dist[i]=Integer.MAX_VALUE;
par[i]=-1;
}
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s]=true;
dist[s]=0;
queue.add(s);
while (queue.size() != 0)
{
s = queue.poll();
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
dist[n]=dist[s]+1;
par[n]=s;
queue.add(n);
}
}
}
}
/**
* Thus api prints a path(showing all the vertices in between s and d
* vertices) from Source vertices s to Destination vertices d
*
* @param s
* @param d
*/
void path(int s,int d)
{
BFS(s);
System.out.print(d);
int tmp=d;
while(tmp!=-1&&tmp!=s){
System.out.print("<-"+par[tmp]);
tmp=par[tmp];
}
System.out.println("\nDistance form "+s+" to "+d+" is : "+dist[d]);
}
/**
* This api prints the diameter of this WebGraph
*/
void diameter()
{
int max=Integer.MIN_VALUE;
for(int j=0;j<V;j++){
BFS(j);
for(int i=0;i<V;i++)
{
if(max<dist[i])
max=dist[i];
}}
System.out.println("Diameter of Graph is : "+max);
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number of vertices:");
int v=in.nextInt();int u,e;
WebGraph g = new WebGraph(v);
System.out.println("Enter number of edges:");
e=in.nextInt();
System.out.println("Enter Edges (u,v)");
for(int i=0;i<e;i++)
{
u=in.nextInt();
v=in.nextInt();
g.addEdge(u, v);
}
g.diameter();
System.out.println("\nEnter source and destination to find min distance :");
int s=in.nextInt();
int d=in.nextInt();
g.path(s,d);
}
}