/
Multisource_Shortest_Path.java
87 lines (62 loc) · 1.84 KB
/
Multisource_Shortest_Path.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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Multisource_Shortest_Path {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n,m,s;
System.out.println("Enter number of vertices, edges and sources");
n = sc.nextInt();
m = sc.nextInt();
s = sc.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n+1];
int[] sources = new int[n+1];
System.out.println("Enter sources");
for (int i = 0;i<s;i++) {
int src;
src = sc.nextInt();
sources[i] = src;
}
System.out.println("Enter the edges");
for(int i = 1;i<=n;i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0;i<m;i++) {
int u,v;
u = sc.nextInt();
v = sc.nextInt();
adj[u].add(v);
adj[v].add(u);
}
int dist[] = new int[n+1];
int vis[] = new int[n+1];
for (int i = 0;i<=n;i++) {
dist[i] = 1000000000;
}
Queue<Integer> q = new LinkedList<Integer>();
for(int i = 0;i<s;i++) {
q.add(sources[i]);
vis[sources[i]] = 1;
}
int lvl = 0;
while (q.size() > 0) {
int sz = q.size();
for(int i = 0;i<sz;i++) {
int node = q.remove();
dist[node] = lvl;
for(int it: adj[node]) {
if(vis[it] == 1) {
continue;
}
vis[it] = 1;
q.add(it);
}
}
lvl++;
}
for (int i = 1;i<=n;i++) {
System.out.println(i + ": " + dist[i]);
}
}
}