AlgorithmsIntermediate

Breadth-First Search (BFS) in Python

Learn Breadth-First Search (BFS) in Python! A beginner-friendly, fun guide to exploring graphs level by level.

Try it yourself

Run this code directly in your browser. Click "Open in full editor" to experiment further.

Loading...

Click Run to see output

Or press Ctrl + Enter

How it works

Breadth-First Search (BFS) is such an amazing and fun algorithm to learn! ๐Ÿš€

How It Works

Imagine you dropped a stone in a calm pond. The ripples spread outwards, forming wider and wider circles, right? That's exactly how BFS works! Instead of running all the way down one single path until you hit a dead end, we explore our immediate surroundings first, level by level. It's super methodical and safe! ๐ŸŒŠ

To make this magic happen, we use a special tool called a Queue (think of a line at a theme park โ€“ First-In-First-Out). We pop a node out of the front of the line, check out its neighbors, and add those new neighbor friends to the back of the line.

We also keep a little notepad called a visited set. This is super important so we don't accidentally walk in circles forever! ๐Ÿ˜…

Time and Space Complexity

  • Time Complexity: O(V + E) where V is our vertices (nodes) and E is our edges (connections). We gracefully visit everyone and every connection exactly once. So efficient! โœจ
  • Space Complexity: O(V) because we just need enough space for our queue and our notepad of visited places.
  • Real World Magic (Use Cases)

    1. Shortest Path: Finding the fastest way out! Because we ripple outwards from the start, the very first time we bump into our target, it is mathematically guaranteed to be the shortest path. Awesome, right?

    2. Social Networks: Ever wonder how apps know your "friends of friends"? Yep, that's BFS in action!

    3. Web Crawlers: Search engines use this to systematically explore the internet, link by link.

    You're going to do great with this! Try running the code above and watch the ripple effect happen right in your console. ๐ŸŽ‰

    Related examples

    Keywords: python bfs, breadth first search python, bfs algorithm python, graph traversal python, shortest path python, python queue bfs