Breadth-first search (BFS)
BFS on a graph starts at a vertex and first visits all its neighbors, then those neighbors' neighbors, and so on, like a ripple. It uses a queue: the starting vertex is enqueued; each round one is dequeued, marked visited, and its not-yet-visited neighbors are enqueued. Since a tree is a special case of a graph, it's the same level-order walk, with one extra care: no repeats.
Unlike a tree, a graph can have cycles: paths that return to the same vertex, like 1-2-3-1. Without care, a traversal would go around forever. That's why a visited set is kept, a hash table with the vertices already seen. Before enqueueing or visiting a vertex, you check whether it's there: in O(1).
Both traversals cost O(|V| + |E|) in time: each vertex is visited once, and in an undirected graph each edge is looked at twice, once from each end. In memory, both are O(|V|): the visited set and the result hold up to |V| vertices, so does the BFS queue, and the DFS recursion can reach |V| levels.
Graph traversals solve very different problems. BFS is for the shortest path in number of steps, like degrees of separation between 2 people, or for finding everything k steps away. DFS is for exploring everything reachable, detecting cycles, or solving mazes and puzzles by trying paths. Both work for checking whether a graph is connected.
