-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathShortestPathUndirectedGraph.java
More file actions
54 lines (40 loc) · 1.45 KB
/
ShortestPathUndirectedGraph.java
File metadata and controls
54 lines (40 loc) · 1.45 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
import java.util.*;
public class ShortestPathUndirectedGraph {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nv = sc.nextInt();
int ne = sc.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(nv);
for (int i = 0; i < nv; i++)
adj.add(new ArrayList<Integer>());
for (int i = 0; i < ne; i++) {
int firstVertex = sc.nextInt();
int secondVertex = sc.nextInt();
adj.get(firstVertex).add(secondVertex);
adj.get(secondVertex).add(firstVertex);
}
int src = sc.nextInt();
sc.close();
int[] dist = shortestPath(adj, nv, src);
for (int i = 0; i < dist.length; i++) {
System.out.print(dist[i]+" ");
}
}
private static int[] shortestPath(ArrayList<ArrayList<Integer>> adj, int nv, int startVertex) {
int[] distance = new int[nv];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[startVertex] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(startVertex);
while (!q.isEmpty()) {
int top = q.poll();
for (int adjacent : adj.get(top)) {
if (distance[top] + 1 < distance[adjacent]) {
distance[adjacent] = distance[top] + 1;
q.add(adjacent);
}
}
}
return distance;
}
}