A weighted graph is a type of graph data structure in which every edge has an associated value called a weight. This weight represents information such as distance, cost, time, or capacity between two vertices. Unlike an unweighted graph, where all edges are treated equally, a weighted graph helps represent relationships with different values. Weighted graphs are widely used in navigation systems, computer networks, transportation, and network optimization. In this article, we will understand weighted graphs, their terminology, types, representations, operations, and implementation using JavaScript.
Table of Contents
What Is a Weighted Graph?
A weighted graph is a graph in which each edge is assigned a numerical value called a weight.
A weighted graph is generally represented as:
G = (V, E, W)
Where:
- G: Represents the graph.
- V: Represents the set of vertices or nodes.
- E: Represents the set of edges connecting vertices.
- W: Represents the weights assigned to the edges.
For example, consider a connection between two cities. If the distance between City A and City B is 50 kilometers, the edge connecting them can have a weight of 50.
The weight can represent different measurements depending on the application.
Some common examples include:
- Distance between two locations.
- Cost of travelling between cities.
- Time required to complete a journey.
- Network bandwidth or communication cost.
- Financial cost between connected entities.
Weighted graphs help solve problems where the value of a connection matters.
How Does a Weighted Graph Work?
In a weighted graph, every edge stores a value along with the connection between two vertices.
Consider a weighted graph with the following edges:
- A — B (10)
- A — C (20)
- B — D (15)
- C — D (5)
These connections indicate that:
- The edge between A and B has a weight of 10.
- The edge between A and C has a weight of 20.
- The edge between B and D has a weight of 15.
- The edge between C and D has a weight of 5.
The weights can be used to calculate the total cost of a path.
For example, the path A → B → D has a total weight of: 10 + 15 = 25
The path A → C → D has a total weight of:
20 + 5 = 25
Both paths have the same total weight.
In real-world applications, algorithms can use these weights to find the shortest, cheapest, or most efficient path.
Basic Terminology of Weighted Graphs
Understanding the terminology of weighted graphs makes it easier to learn graph algorithms and solve programming problems.
- Vertex: A vertex is an individual node in a graph. It represents an object, location, device, or entity.
- Edge: An edge is a connection between two vertices. In a weighted graph, every edge has an associated weight.
- Weight: A weight is a numerical value assigned to an edge. It can represent distance, cost, time, or another measurable quantity.
- Weighted Path: A weighted path is a sequence of connected vertices where each edge has a weight. The total weight of the path is calculated by adding the weights of all edges along that path.
- Shortest Path: The shortest path is a path between two vertices with the minimum total weight. The meaning of shortest depends on the edge weights. For example, it may represent the minimum distance or minimum travel cost.
- Negative Weight: A negative weight is an edge weight whose value is less than zero. Negative weights can represent situations such as financial gains or cost adjustments. Some shortest-path algorithms support negative weights, while others do not.
- Weighted Degree: In an undirected weighted graph, the weighted degree of a vertex is the sum of the weights of its incident edges. For directed weighted graphs, incoming and outgoing edge weights can be considered separately.
- Directed Weighted Graph: A directed weighted graph contains edges with both a direction and an associated weight.
- Undirected Weighted Graph: An undirected weighted graph contains edges without a direction, and every edge has an associated weight.
- Minimum Spanning Tree: A Minimum Spanning Tree (MST) is a spanning tree of a connected, undirected, weighted graph with the minimum possible total edge weight.
Types of Weighted Graphs
Weighted graphs can be classified based on the direction of their edges and the values assigned to them.
1. Directed Weighted Graph: A directed weighted graph contains edges with a specific direction and an associated weight.
For example, an edge A → B with weight 10 represents a connection from A to B with a cost of 10. It does not automatically create a reverse connection.
2. Undirected Weighted Graph: An undirected weighted graph contains edges without a specific direction. The weight applies to the connection between both vertices.
For example, an edge between A and B with weight 10 allows movement in both directions with the same edge weight.
3. Positive Weighted Graph: A positive weighted graph contains only positive edge weights.
These graphs are commonly used in distance calculations and transportation systems.
4. Negative Weighted Graph: A negative weighted graph contains one or more negative edge weights. Such graphs can be used in financial models and optimization problems.
5. Mixed Weighted Graph: A graph may contain both positive and negative edge weights. Algorithms used on such graphs must handle negative weights correctly.
Weighted Graph Representation
A weighted graph can be represented using different data structures in programming.
The two most commonly used representations are:
- Adjacency List.
- Adjacency Matrix.
Both representations store vertices, edges, and their associated weights.
Adjacency List Representation
An adjacency list stores each vertex along with its neighboring vertices and the corresponding edge weights.
For example, consider an undirected weighted graph with these edges:
- A — B (10)
- A — C (20)
- B — D (15)
- C — D (5)
The adjacency list is:
- A: (B, 10), (C, 20)
- B: (A, 10), (D, 15)
- C: (A, 20), (D, 5)
- D: (B, 15), (C, 5)
In JavaScript, an adjacency list can be implemented using a Map.
// This program creates a weighted undirected graph using an adjacency list.
const graph = new Map();
function addVertex(vertex) {
if (!graph.has(vertex)) {
graph.set(vertex, []);
}
}
function addEdge(vertex1, vertex2, weight) {
addVertex(vertex1);
addVertex(vertex2);
graph.get(vertex1).push({
vertex: vertex2,
weight: weight
});
graph.get(vertex2).push({
vertex: vertex1,
weight: weight
});
}
addEdge("A", "B", 10);
addEdge("A", "C", 20);
addEdge("B", "D", 15);
addEdge("C", "D", 5);
console.log(graph);
Output:
Map(4) {
'A' => [
{ vertex: 'B', weight: 10 },
{ vertex: 'C', weight: 20 }
],
'B' => [
{ vertex: 'A', weight: 10 },
{ vertex: 'D', weight: 15 }
],
'C' => [
{ vertex: 'A', weight: 20 },
{ vertex: 'D', weight: 5 }
],
'D' => [
{ vertex: 'B', weight: 15 },
{ vertex: 'C', weight: 5 }
]
}
In this implementation:
- addVertex() creates a vertex if it does not already exist.
- addEdge() creates a connection between two vertices.
- Each connection stores the neighboring vertex and its weight.
- Both adjacency lists are updated because this example uses an undirected graph.
For a directed weighted graph, only the source vertex's adjacency list would be updated.
Adjacency Matrix Representation
An adjacency matrix represents a weighted graph using a two-dimensional array.
Each row and column represents a vertex. If an edge exists between two vertices, the corresponding matrix entry stores its weight. If no edge exists, the entry stores a special value such as Infinity or null.
For example, consider an undirected weighted graph with these edges:
- A — B (10)
- A — C (20)
- B — D (15)
- C — D (5)
The adjacency matrix is:
| Vertex | A | B | C | D |
|---|---|---|---|---|
| A | 0 | 10 | 20 | ∞ |
| B | 10 | 0 | ∞ | 15 |
| C | 20 | ∞ | 0 | 5 |
| D | ∞ | 15 | 5 | 0 |
In this matrix:
- A to B and B to A both have a weight of 10.
- A to C and C to A both have a weight of 20.
- B to D and D to B both have a weight of 15.
- C to D and D to C both have a weight of 5.
- Infinity indicates that no direct edge exists between those vertices.
The adjacency matrix of an undirected weighted graph is symmetric when the same weight applies in both directions.
JavaScript Example:
// This program represents an undirected weighted graph using an adjacency matrix.
const vertices = ["A", "B", "C", "D"];
const matrix = [
[0, 10, 20, Infinity],
[10, 0, Infinity, 15],
[20, Infinity, 0, 5],
[Infinity, 15, 5, 0]
];
console.log(matrix);
Output:
[
[0, 10, 20, Infinity],
[10, 0, Infinity, 15],
[20, Infinity, 0, 5],
[Infinity, 15, 5, 0]
]
An adjacency matrix is useful when the graph is dense or when checking the weight of a particular edge needs to be performed quickly.
Weighted Graph Implementation in JavaScript
A weighted graph can be implemented using a JavaScript class and a Map data structure.
The following example creates an undirected weighted graph and supports adding vertices, adding weighted edges, and displaying connections.
// This program implements a weighted undirected graph using a JavaScript class.
class WeightedGraph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(vertex1, vertex2, weight) {
this.addVertex(vertex1);
this.addVertex(vertex2);
this.adjacencyList.get(vertex1).push({
vertex: vertex2,
weight: weight
});
this.adjacencyList.get(vertex2).push({
vertex: vertex1,
weight: weight
});
}
display() {
for (const [vertex, neighbors] of this.adjacencyList) {
console.log(`${vertex} -> ${JSON.stringify(neighbors)}`);
}
}
}
const graph = new WeightedGraph();
graph.addEdge("A", "B", 10);
graph.addEdge("A", "C", 20);
graph.addEdge("B", "D", 15);
graph.addEdge("C", "D", 5);
graph.display();
Output:
A -> [{"vertex":"B","weight":10},{"vertex":"C","weight":20}]
B -> [{"vertex":"A","weight":10},{"vertex":"D","weight":15}]
C -> [{"vertex":"A","weight":20},{"vertex":"D","weight":5}]
D -> [{"vertex":"B","weight":15},{"vertex":"C","weight":5}]
In this implementation:
-
The constructor initializes an empty adjacency list.
-
addVertex() adds a new vertex.
-
addEdge() creates a weighted connection between two vertices.
-
display() prints each vertex along with its neighboring vertices and edge weights.
This example uses an undirected graph. For a directed weighted graph, the reverse adjacency entry should not be added.
Operations on a Weighted Graph
Several operations can be performed on a weighted graph to manage its vertices, edges, and weights.
1. Add Vertex: Adds a new vertex to the graph.2. Add Weighted Edge: Creates a connection between two vertices and assigns a weight to that connection.
3. Remove Edge: Removes a connection between two vertices. In an undirected graph, the edge must be removed from both adjacency lists.
4. Update Edge Weight: Changes the weight assigned to an existing edge.
5. Search Vertex: Checks whether a particular vertex exists in the graph.
6. Find Shortest Path: Finds the path between two vertices with the minimum total weight.
Common shortest-path algorithms include:
Dijkstra's Algorithm.
Bellman-Ford Algorithm.
Floyd-Warshall Algorithm.
7. Find Minimum Spanning Tree: Finds a minimum-weight set of edges that connects all vertices in a connected, undirected, weighted graph without forming cycles.
Common algorithms include:
Prim's Algorithm.
Kruskal's Algorithm.
Difference Between Weighted and Unweighted Graphs
Weighted and unweighted graphs are two types of graph data structures. Their main difference is whether edges have associated values.
| Weighted Graph | Unweighted Graph |
|---|---|
| Every edge has an associated weight. | Edges do not have associated weights. |
| Weights represent distance, cost, or time. | All edges are treated equally. |
| Used for cost-based path calculations. | Used for basic connectivity problems. |
| Shortest paths depend on total edge weights. | Shortest paths are generally measured by the number of edges. |
| Can contain positive or negative weights. | Does not assign numerical weights to edges. |
| Examples include road distances and network costs. | Examples include basic friendship connections. |
Applications of Weighted Graphs
Weighted graphs are widely used in computer science and real-world applications where connections have different costs or values.
- Navigation Systems: Navigation applications use weighted graphs to represent roads and distances between locations. The weights can represent distance, travel time, or estimated cost.
- Transportation Networks: Weighted graphs represent connections between cities, railway stations, and airports. Edge weights can represent travel distance, ticket cost, or journey duration.
- Computer Networks: Weighted graphs represent network connections where weights may indicate latency, bandwidth-related costs, or communication delays.
- Network Optimization: Weighted graphs are used to find efficient connections between devices or locations. Minimum Spanning Tree algorithms help reduce the total connection cost.
- Social Networks: Weighted graphs can represent the strength of relationships between users, such as interaction frequency or similarity scores.
- Project Scheduling: Weighted graphs can represent dependencies and the time or cost associated with different activities.
- Recommendation Systems: Weighted graphs can represent relationships between users, products, and interests. Weights may indicate similarity or recommendation strength.
Advantages of Weighted Graphs
Weighted graphs provide several benefits when representing relationships with different values.
- They represent real-world relationships more accurately when connections have different costs.
- They help calculate the shortest or least expensive paths.
- They support network optimization algorithms.
- They can represent distance, time, cost, and other measurements.
- They are useful in navigation and transportation systems.
- They support advanced algorithms such as Dijkstra's, Bellman-Ford, Prim's, and Kruskal's algorithms.
Disadvantages of Weighted Graphs
Despite their usefulness, weighted graphs also have some limitations.
- They are more complex to implement than basic unweighted graphs.
- Choosing an appropriate weight can be difficult.
- Some shortest-path algorithms do not support negative edge weights.
- Large weighted graphs can require significant memory and processing time.
- Incorrect or outdated weights can produce unreliable results.
Time and Space Complexity
The complexity of a weighted graph depends on its representation and the operation being performed.
Let:
- V = Number of vertices.
- E = Number of edges.
| Operation | Adjacency List | Adjacency Matrix |
|---|---|---|
| Add Vertex | O(1) average | O(V²) if resizing |
| Add Edge | O(1) average | O(1) |
| Check Edge | O(degree) | O(1) |
| Remove Edge | O(degree) | O(1) |
| Space Complexity | O(V + E) | O(V²) |
The adjacency list is generally preferred for sparse weighted graphs because it stores only existing edges and their weights.
The adjacency matrix is useful for dense graphs or when checking whether an edge exists and retrieving its weight need to be performed quickly.
Common Mistakes to Avoid
-
Confusing edge weights with vertex values: A weight is associated with an edge, not necessarily with the vertex it connects.
-
Ignoring the direction of weighted edges: In a directed weighted graph, an edge from A to B does not automatically create a reverse edge from B to A.
-
Using the wrong shortest-path algorithm: Dijkstra's algorithm assumes non-negative edge weights. Bellman-Ford can handle negative edges but reports a reachable negative-weight cycle when one exists.
-
Forgetting to update both connections: When implementing an undirected weighted graph using an adjacency list, both vertices must store the corresponding edge and weight.
-
Treating missing edges as zero: A zero-weight edge can be valid. Use a separate representation such as Infinity or null to indicate that no edge exists.
Conclusion
A weighted graph is an important data structure used to represent connections with associated values such as distance, cost, and time. It is widely used in navigation systems, transportation networks, computer networks, and optimization problems. Understanding weighted graph terminology, types, representations, operations, and implementation provides a strong foundation for learning advanced graph algorithms and solving data structure and algorithm problems.
Frequently Asked Questions
1. What is a weighted graph?
A weighted graph is a graph in which every edge has an associated numerical value called a weight.
2. What does the weight represent in a graph?
A weight can represent distance, cost, time, capacity, or another measurable value associated with an edge.
3. What is the difference between weighted and unweighted graphs?
A weighted graph assigns values to its edges, while an unweighted graph treats all edges equally.
4. Which algorithms are used in weighted graphs?
Common algorithms include Dijkstra's, Bellman-Ford, Floyd-Warshall, Prim's, and Kruskal's algorithms.
5. Can a weighted graph contain negative weights?
Yes. A weighted graph can contain negative edge weights. However, algorithms such as Dijkstra's do not support negative weights, so an appropriate algorithm must be selected.
0 Comments