A graph represents objects and relationships between them. The objects are vertices, and the relationships are edges.

Graphs are useful because many problems are really about reachability, connection, dependency, movement, or cost between things.

Core Idea

A graph does not have to look like a road map. A graph can represent people connected by friendships, tasks connected by prerequisites, web pages connected by links, or states connected by possible moves.

Once a problem is modeled as a graph, graph algorithms can answer questions about traversal, shortest paths, components, cycles, and ordering.

Python Example

graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A"],
    "D": ["B"],
}

This dictionary represents each vertex with the vertices connected to it.

Common Confusions

A graph is a model, not only a drawing. The same graph can be stored as a dictionary, a list of edges, an adjacency matrix, or another representation.

A tree is a special kind of graph. Not every graph is a tree because graphs may have cycles, disconnected parts, or arbitrary relationships.

When To Use It

Use graph thinking when the problem involves relationships, movement from one state to another, dependencies, networks, connected groups, or paths.