cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 62 of 218
Ideas this builds on
Graphs62 / 218

A graph is a language for legal moves

Picture

A graph says which things are connected. For a search problem, a vertex can represent a situation and an edge a legal move. Rooms and roads are easy examples, but a vertex might also mean a word, a puzzle arrangement, or a location together with remaining fuel.

Predict

A rectangular board allows four-directional movement. Must you build a dictionary containing every square and every neighboring square before running a graph search?

Reveal the reasoning

No. Generate neighbors from coordinates when needed. The graph is implicit in the movement rule. A graph model and a stored adjacency list are not the same thing.

Go deeper: define vertices, edges, and the answer
def neighbors(row, col, rows, cols):
    for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        nr, nc = row + dr, col + dc
        if 0 <= nr < rows and 0 <= nc < cols:
            yield nr, nc

assert set(neighbors(0, 0, 2, 3)) == {(1, 0), (0, 1)}

Before choosing a traversal, answer three modeling questions. What information makes a vertex distinct? Are moves one-way or two-way? Do edges have equal cost, varying cost, or no relevant cost?

A finite undirected tree is connected and has no cycles, hence a unique simple path between any pair of vertices. General graphs can have cycles, disconnected pieces, and several paths to one vertex. Those differences change visitation rules.

For an adjacency-list graph, storing all vertices and edges costs O(V+E) space. A four-neighbor grid has at most four outgoing moves per square, so enumerating its full adjacency also has linear size in the number of cells. An implicit graph avoids prebuilding edges; it does not eliminate the work of searching reachable states.

Recognition signal: if you can describe a legal “next situation,” a graph model may exist even when the problem never says “graph.” This does not mean BFS is automatically appropriate; the answer’s objective and move costs still matter.

Analogy limit: a vertex is not always a physical place. Merging all fuel levels at one location can create a graph that solves the wrong problem.

Change one rule

Doors lock permanently behind you. Is the room number alone still a sufficient vertex?

Check the variation

Not generally. Which doors have locked changes legal future moves. You may need additional state, potentially a much larger set of situations than physical rooms.

Connect

BFS explores equal-cost layers. Dependencies use directed edges to express prerequisites. Budget DP expands a location into several resource states.