DSA Lab

Graph BFS and DFS

Breadth-first and depth-first search are the two basic ways to visit every node of a graph. BFS uses a queue and spreads out in rings; DFS uses a stack (or recursion) and goes as deep as it can before backing up.

Graph BFS and DFS: how it works

In this tool: queue vs stack, visit order. Put in your own values and watch it change. Each operation runs one step at a time and says in plain words what happened, with its calculation worked out. The code is shown in Python, C, C++ or Java with the line that just ran marked, and an Understand it panel gives the idea, why it works, the cost of each operation, common mistakes and a short quiz.

Lessons that use it

  • Graphs (Data Structures)Vertices and edges, directed and undirected, stored as an adjacency matrix or as adjacency lists.
  • Graph traversal: BFS and DFS (Data Structures)Breadth-first search with a queue finds the fewest edges to every vertex; depth-first search goes deep with recursion.
  • Graph patterns (Interview Prep)Grids are graphs: counting islands with DFS or BFS, shortest paths in unweighted graphs with BFS, and ordering tasks with topological sort.
  • Graphs with the STL (Competitive)Adjacency lists as vector<vector<int>>, BFS with queue, shortest paths on a grid, and Dijkstra with a priority_queue.