What Is a Weighted Graph: Definition and Examples
weighted graph is a type of graph where each connection (edge) between points (nodes) has a number called a weight. These weights represent values like cost, distance, or time, helping to measure how strong or important each connection is.How It Works
A weighted graph is like a map where cities are points and roads between them have numbers showing distances or travel costs. Instead of just knowing which cities connect, you also know how far or expensive it is to travel between them.
Imagine you want to find the shortest path from your home to a friend's house. The weighted graph helps by showing not just the roads but also how long each road takes, so you can pick the quickest route. Each edge's weight guides decisions based on the value it represents.
Example
This example shows a weighted graph using a dictionary where keys are nodes and values are lists of connected nodes with their weights.
graph = {
'A': [('B', 5), ('C', 3)],
'B': [('A', 5), ('C', 2), ('D', 6)],
'C': [('A', 3), ('B', 2), ('D', 7)],
'D': [('B', 6), ('C', 7)]
}
for node, edges in graph.items():
print(f"Node {node} connects to:")
for (neighbor, weight) in edges:
print(f" - {neighbor} with weight {weight}")When to Use
Weighted graphs are useful when you need to consider the cost or value of connections, not just their existence. For example, they help in:
- Finding the shortest or cheapest path in maps and GPS navigation.
- Modeling networks where edges have capacities or costs, like internet routing or transportation.
- Planning projects where tasks depend on others with different durations or costs.
Whenever you want to measure or optimize based on connection values, weighted graphs are the right choice.
Key Points
- A weighted graph assigns a number (weight) to each edge.
- Weights represent things like distance, cost, or time.
- They help find optimal paths or analyze networks with varying connection values.
- Weighted graphs can be directed or undirected depending on edge direction.