Python 3D Academyবাংলা

Graph Basics: BFS & DFS in Python

Chapter 51: Graph Basics: BFS & DFS

7 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Vertices and edges; adjacency lists and matrices

    A graph is a set of vertices joined by edges, and a program usually stores it as an adjacency list (each vertex with the list of its neighbours) or an adjacency matrix (a grid of 0s and 1s saying which pairs are joined).

  2. Breadth-first search: the fewest steps

    BFS keeps a queue of vertices to process and a record of every vertex already seen; it takes the front vertex and gives each neighbour not yet seen a distance one more than its own, putting it at the back, so vertices come out in order of distance.

  3. Depth-first search: exploring a maze

    DFS keeps the vertices still to try on a stack (or uses the call stack, by recursion): it takes the most recently added vertex, visits it if it is new, and adds its unvisited neighbours, so it always goes deeper before going wider.

  4. Grids as graphs: islands and flood fill

    In a grid, each cell (r, c) is a vertex whose neighbours are the cells one step up, down, left and right that are inside the grid; an island is a connected component of land cells, and flood fill is one search that changes every cell it reaches.

  5. Two teams, and copying a graph

    Colour the graph with a BFS, giving each newly reached vertex the opposite team of the vertex it was reached from, and if an edge ever joins two vertices of the same team, no split exists; to copy a graph, walk it once, keeping a dict from each original node to its copy so that a node met twice is copied only once.

  6. BFS from many starts, and graphs you never build: word ladders

    A multi-source BFS puts every start in the queue at distance 0 before the search begins, so each vertex is reached first, and labelled, by its nearest start; and an implicit graph finds a vertex's neighbours by rule (here: words that differ in one letter) instead of from a stored list.

  7. Using every edge once: Euler paths

    An Euler path exists when the degrees allow it (in an undirected graph, every vertex has an even degree, or exactly two have an odd one), and Hierholzer's algorithm finds it by walking along unused edges until it gets stuck, adding each stuck vertex to the route, and reading the route backwards at the end.