A weighted graph attaches a cost, distance, time, capacity, or score to each edge.

Weights matter because the best path may no longer be the path with the fewest edges.

Core Idea

In an unweighted graph, moving across one edge has the same cost as moving across any other edge. In a weighted graph, different edges can have different costs.

This changes which algorithms are valid. BFS gives shortest paths by edge count, but weighted shortest paths usually need different tools.

Python Example

graph = {
    "A": [("B", 5), ("C", 2)],
    "B": [("D", 1)],
    "C": [("D", 10)],
    "D": [],
}

Each neighbor is stored with the edge weight needed to reach it.

Common Confusions

Weight does not always mean distance. It can mean cost, time, risk, probability penalty, or any numeric value defined by the problem.

Negative weights require special care. Some shortest path algorithms assume all weights are non-negative.

When To Use It

Use a weighted graph when movement or relationship cost matters. If every move has the same cost, an unweighted graph may be enough.