# Weighted Graph Implementation – JAVA

What is Weighted Graph?

A Graph is called weighted graph when it has weighted edges which means there are some cost associated with each edge in graph.

Example: Implementation:

• Each edge of a graph has an associated numerical value, called a weight.
• Usually, the edge weights are nonnegative integers.
• Weighted graphs may be either directed or undirected.
• The weight of an edge is often referred to as the “cost” of the edge.
• Will create an Edge class to put weight on each edge

Complete Code:

 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 [] adjacencylist; Graph(int vertices) { this.vertices = vertices; adjacencylist = new LinkedList[vertices]; //initialize adjacency lists for all the vertices for (int i = 0; i (); } } 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 list = adjacencylist[i]; for (int j = 0; j

view raw
WeightedGraph.java
hosted with ❤ by GitHub

Output:

```vertex-0 is connected to 2 with weight 3
vertex-0 is connected to 1 with weight 4
vertex-1 is connected to 2 with weight 5
vertex-1 is connected to 3 with weight 2
vertex-2 is connected to 3 with weight 7
vertex-3 is connected to 4 with weight 2
vertex-4 is connected to 5 with weight 6
vertex-4 is connected to 1 with weight 4
vertex-4 is connected to 0 with weight 4
```

Reference: here