Graph Theory37 sections · 1633 units
Open in Course

The Visited Array

The Chalk Mark

To prevent infinite loops in graphs with cycles, you track which vertices you have already visited. Use a boolean array: visited[u] = true means you have been to vertex uu. Before recursing to a neighbor, check if it is already visited.

If yes, skip it. If no, mark it visited and recurse. This simple mechanism prevents your DFS from looping forever. Without it, a graph like 121 \leftrightarrow 2 would cause infinite recursion: visit 11, go to 22, go back to 11, go to 22, forever.

photo_۲۰۲۵-۱۲-۲۶_۰۱-۲۹-۴۴ (2).jpg