-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleSourceShort
More file actions
86 lines (85 loc) · 2.81 KB
/
SingleSourceShort
File metadata and controls
86 lines (85 loc) · 2.81 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
import java.util.*;
public class SingleSourceShort
{
static ArrayList<ArrayList<ArrayList<Integer>>> constructAdj(int[][] edges, int V)
{
ArrayList<ArrayList<ArrayList<Integer>>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges)
{
int u = edge[0];
int v = edge[1];
int wt = edge[2];
ArrayList<Integer> e1 = new ArrayList<>();
e1.add(v);
e1.add(wt);
adj.get(u).add(e1);
ArrayList<Integer> e2 = new ArrayList<>();
e2.add(u);
e2.add(wt);
adj.get(v).add(e2);
}
return adj;
}
// Dijkstra’s Algorithm
static int[] dijkstra(int V, int[][] edges, int src)
{
ArrayList<ArrayList<ArrayList<Integer>>> adj = constructAdj(edges, V);
PriorityQueue<ArrayList<Integer>> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a.get(0)));
int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
ArrayList<Integer> start = new ArrayList<>();
start.add(0);
start.add(src);
pq.offer(start);
while (!pq.isEmpty()) {
ArrayList<Integer> curr = pq.poll();
int d = curr.get(0);
int u = curr.get(1);
for (ArrayList<Integer> neighbor : adj.get(u))
{
int v = neighbor.get(0);
int weight = neighbor.get(1);
if (dist[v] > dist[u] + weight) {
dist[v] = dist[u] + weight;
ArrayList<Integer> temp = new ArrayList<>();
temp.add(dist[v]);
temp.add(v);
pq.offer(temp);
}
}
}
return dist;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = sc.nextInt();
System.out.print("Enter number of edges: ");
int E = sc.nextInt();
int[][] edges = new int[E][3];
System.out.println("\nEnter each edge as: u v weight");
for (int i = 0; i < E; i++)
{
edges[i][0] = sc.nextInt(); // u
edges[i][1] = sc.nextInt(); // v
edges[i][2] = sc.nextInt(); // weight
}
System.out.print("\nEnter source vertex: ");
int src = sc.nextInt();
int[] result = dijkstra(V, edges, src);
System.out.println("\nShortest distances from source " + src + ":");
for (int d : result)
{
if (d == Integer.MAX_VALUE)
System.out.print("INF ");
else
System.out.print(d + " ");
}
sc.close();
}
}