Graph Algorithms — ELI5

Think about a subway map. There are stations (dots) and train lines connecting them (lines). If you want to get from your home station to the zoo, you need to figure out which connections to take. That is exactly what a computer does with a graph.

A graph is just dots connected by lines. The dots are called nodes (like stations), and the lines are called edges (like train routes). Graphs describe tons of real things:

  • A social network: every person is a dot, and friendships are lines.
  • A road map: every intersection is a dot, and roads are lines.
  • The internet: every website is a dot, and links between them are lines.

Now, the big question is: how do you explore a graph?

There are two main ways:

Breadth-first search (BFS) is like ripples in a pond. You start at one dot and visit all the dots one step away first. Then all the dots two steps away. Then three. This finds the shortest path when every line is the same length.

Depth-first search (DFS) is like exploring a maze. You pick a path and follow it as far as you can. When you hit a dead end, you backtrack and try a different path. This is great for exploring everything reachable from a starting point.

Python makes graphs easy because you can represent them with simple dictionaries — each dot maps to a list of dots it connects to.

One thing to remember: Whenever you have things connected to other things and need to find paths or explore relationships, you are working with a graph — even if nobody calls it that.

pythonalgorithmsgraphs

See Also