forked from golumall/Graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeighted Undirected Graph.java
More file actions
62 lines (62 loc) · 1.13 KB
/
Weighted Undirected Graph.java
File metadata and controls
62 lines (62 loc) · 1.13 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
import java.util.Scanner;
import java.util.LinkedList;
class WeightedUndirectedGraph
{
static class Edge
{
int source;
//int dest;
int weight;
public Edge(int source,int weight)
{
this.source=source;
//this.dest=dest;
this.weight=weight;
}
}
int v;
LinkedList<Edge> adj[];
WeightedUndirectedGraph(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int source,int dest,int weight)
{
Edge ob=new Edge(dest,weight);
Edge ob1=new Edge(source,weight);
adj[source].add(ob);
adj[dest].add(ob1);
}
void printGraph()
{
int i=0;
for(i=0;i<v;i++)
{
System.out.print(i);
for(Edge ob:adj[i])
{
System.out.print("->"+ob.source+"-> Weight "+ob.weight);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
WeightedUndirectedGraph g=new WeightedUndirectedGraph(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
int weight=sc.nextInt();
g.addEdge(src,dest,weight);
}
g.printGraph();
}
}