Last active
April 22, 2022 10:49
-
-
Save thmain/10f6f48145c768620da2945670c9dfe4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
public class WeightedGraph { | |
static class Edge { | |
int source; | |
int destination; | |
int weight; | |
public Edge(int source, int destination, int weight) { | |
this.source = source; | |
this.destination = destination; | |
this.weight = weight; | |
} | |
} | |
static class Graph { | |
int vertices; | |
LinkedList<Edge> [] adjacencylist; | |
Graph(int vertices) { | |
this.vertices = vertices; | |
adjacencylist = new LinkedList[vertices]; | |
//initialize adjacency lists for all the vertices | |
for (int i = 0; i <vertices ; i++) { | |
adjacencylist[i] = new LinkedList<>(); | |
} | |
} | |
public void addEgde(int source, int destination, int weight) { | |
Edge edge = new Edge(source, destination, weight); | |
adjacencylist[source].addFirst(edge); //for directed graph | |
} | |
public void printGraph(){ | |
for (int i = 0; i <vertices ; i++) { | |
LinkedList<Edge> list = adjacencylist[i]; | |
for (int j = 0; j <list.size() ; j++) { | |
System.out.println("vertex-" + i + " is connected to " + | |
list.get(j).destination + " with weight " + list.get(j).weight); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
int vertices = 6; | |
Graph graph = new Graph(vertices); | |
graph.addEgde(0, 1, 4); | |
graph.addEgde(0, 2, 3); | |
graph.addEgde(1, 3, 2); | |
graph.addEgde(1, 2, 5); | |
graph.addEgde(2, 3, 7); | |
graph.addEgde(3, 4, 2); | |
graph.addEgde(4, 0, 4); | |
graph.addEgde(4, 1, 4); | |
graph.addEgde(4, 5, 6); | |
graph.printGraph(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment