Graph
Граф
A graph models objects and the connections between them. The objects are called vertices, and the connections are called edges: in a flight network, airports are vertices and direct flights are edges.
What a graph represents
A graph captures relationships rather than an order or a hierarchy. We write it as G = (V, E), where V is the set of vertices (also called nodes) and E is the set of edges. An edge connects two vertices, but you can reach a vertex without a direct edge by following a path through intermediate vertices. A vertex with no incident edges is isolated; it still belongs to the graph.
An undirected edge can be followed either way. A directed edge from u to v does not imply that you can go back from v to u. Either kind of graph can be weighted: each edge can carry a value such as a fare or travel time. Decide what an edge means before choosing an algorithm.
How to store one
An adjacency list records each vertex's neighbors, using O(|V| + |E|) space. To list the outgoing neighbors of a vertex, read just its own list. For an undirected edge between two distinct vertices, each endpoint appears in the other's list. This is a good default for sparse graphs, where relatively few pairs are connected.
An adjacency matrix gives every ordered pair of vertices a cell. It uses O(|V|²) space even when most cells are empty, but it can answer “Is there an edge from u to v?” in O(1) time when the vertex indices are known. An edge list is another option: it stores the edges directly, but finding a vertex's neighbors may require scanning the entire list.
Example: counting flight legs
flights = {
"A": ["B", "C"],
"B": ["D"],
"C": [],
"D": ["A"],
}
From A, breadth-first search (BFS) discovers B and C in one leg and D in two. The route A → B → D uses the fewest legs, but that alone tells you nothing about its fare. If the goal is to minimize the sum of nonnegative fares, use Dijkstra's algorithm instead. Notice that A → C exists even though C has no outgoing flights.
Recognizing graph problems in interviews
Build dependencies, transit routes, and mazes all fit the graph model. Interview prompts may give you a grid instead of an explicit graph: treat open cells as vertices and legal moves as edges. You can generate neighbors as needed rather than building an adjacency list first.
Before coding, clarify whether edges are directed and whether the task is about reachability, fewest steps, or lowest total cost. In BFS, mark vertices visited when you enqueue them so two different neighbors don't queue the same vertex. A search from one start only visits reachable vertices; if you're counting connected components in an undirected graph, start a new search from each still-unvisited vertex.