Medium Graphs

DFS Graph

Traverses a graph depth-first starting from node 0, using an explicit LIFO stack: it visits the start node, dives into one unvisited neighbor as deep as possible, then backtracks to explore the next one — the same building block used to detect cycles and find connected components. Receives the graph as a square adjacency matrix, where a nonzero value at row i, column j marks an edge between nodes i and j (0 means no edge). Returns the node indices in the order they were visited; nodes unreachable from node 0 are never visited.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References