Depth-first search
Поиск в глубину
An algorithm for exploring a graph or tree by following one branch as far as possible, then backing up to try another branch.
Also known as: DFS
What depth-first search does
Depth-first search (DFS) explores one branch before moving on to the next. Suppose A has neighbors B and C, and B leads to D. If DFS chooses B first, it reaches D before visiting C, even though C is only one edge away from A. The algorithm prioritizes continuing the current branch, not visiting the closest vertex.
How the traversal works
Start at a vertex and mark it as visited. For each neighbor you haven't visited, run the same procedure from that neighbor. When there are no more unvisited neighbors, return to the previous vertex and resume checking its neighbors. Marking vertices before exploring their neighbors prevents a cycle from sending the search around the same loop indefinitely.
Recursion uses the call stack to remember where to resume. An iterative implementation can store that information in an explicit stack instead, which is useful for graphs deep enough to exceed the language's recursion limit. The traversal order depends on the order in which you consider neighbors; DFS does not prescribe a single order.
Example in Python
This version uses an adjacency list: graph[v] lists the vertices you can reach by following one outgoing edge from v.
def dfs(graph, start):
visited = set()
order = []
def visit(vertex):
visited.add(vertex)
order.append(vertex)
for neighbor in graph.get(vertex, []):
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
print(dfs({'A': ['B', 'C'], 'B': ['D']}, 'A'))
# ['A', 'B', 'D', 'C']
A single call covers only the vertices reachable from the start. To visit the whole graph, loop over all vertices and start a new traversal from each still-unvisited vertex, sharing the same visited set across traversals. With adjacency lists, a full traversal takes O(V + E) time: each vertex is visited once and the algorithm scans all neighbor lists. The visited set and call stack use O(V) extra space in the worst case, excluding the graph and any returned output.
Where DFS fits
Use DFS to check reachability or find connected components in an undirected graph. In a directed acyclic graph, reversing the order in which vertices finish gives a topological ordering. That is different from reversing the order returned by the example, which records when each vertex is first reached. If you need a path with the fewest edges, use breadth-first search (BFS) instead: it explores vertices by distance from the start.
What interviewers look for
A common interview problem asks you to count islands in a grid. Treat each land cell as a vertex and connect cells that share a side. Scan the grid and start DFS whenever you encounter unvisited land; that traversal marks an entire island, so the number of starts is the answer. Clarify whether diagonals count as neighbors and whether you're allowed to mark cells directly in the input grid.