You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Depth-First Search (DFS) is the second fundamental graph traversal algorithm. While BFS explores level by level, DFS explores as deep as possible along each branch before backtracking. DFS uses a stack (LIFO) — either explicitly or implicitly through recursion.
Starting from a source vertex, DFS follows this strategy:
DFS goes as deep as possible before backtracking — it follows one path all the way to the end before trying another.
PROCEDURE DFS(graph, v, visited)
ADD v TO visited
OUTPUT v
FOR EACH neighbour OF v IN graph
IF neighbour NOT IN visited THEN
DFS(graph, neighbour, visited)
END IF
END FOR
END PROCEDURE
To start: DFS(graph, startVertex, emptySet)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.