bfs

📰 Medium · Python

Learn to implement Breadth-First Search (BFS) algorithm in Python to traverse graphs or matrices level by level, starting from a given origin point.

intermediate Published 19 Apr 2026
Action Steps
  1. Import necessary modules, including `collections` for the `deque` data structure.
  2. Define the possible movements (e.g., up, down, left, right) in the graph or matrix.
  3. Initialize a queue with the origin point and a set to track visited points.
  4. Implement the BFS loop, where you dequeue a point, print or process it, and then enqueue its unvisited neighbors.
  5. Use conditional statements to handle boundary cases and avoid revisiting points.
Who Needs to Know This

This benefits software engineers and data scientists who need to solve graph or matrix traversal problems, especially in areas like network analysis, pathfinding, or image processing.

Key Insight

💡 BFS traverses a graph or matrix level by level, ensuring that all points at a given distance from the origin are visited before moving further away.

Share This
🚀 Implement BFS in Python to efficiently traverse graphs & matrices! 📈

Key Takeaways

Learn to implement Breadth-First Search (BFS) algorithm in Python to traverse graphs or matrices level by level, starting from a given origin point.

Full Article

Title: bfs

URL Source: https://medium.com/@kiancaca/bfs-669fbc67342c?source=rss------python-5

Published Time: 2026-04-19T21:39:57Z

Markdown Content:
# bfs - Chiahui Chen - Medium

[Sitemap](https://medium.com/sitemap/sitemap.xml)

[Open in app](https://play.google.com/store/apps/details?id=com.medium.reader&referrer=utm_source%3DmobileNavBar&source=post_page---top_nav_layout_nav-----------------------------------------)

Sign up

[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&source=post_page---top_nav_layout_nav-----------------------global_nav------------------)

[](https://medium.com/?source=post_page---top_nav_layout_nav-----------------------------------------)

Get app

[Write](https://medium.com/m/signin?operation=register&redirect=https%3A%2F%2Fmedium.com%2Fnew-story&source=---top_nav_layout_nav-----------------------new_post_topnav------------------)

[Search](https://medium.com/search?source=post_page---top_nav_layout_nav-----------------------------------------)

Sign up

[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&source=post_page---top_nav_layout_nav-----------------------global_nav------------------)

![Image 1](https://miro.medium.com/v2/resize:fill:32:32/1*dmbNkD5D-u45r44go_cf0g.png)

# bfs

[![Image 2: Chiahui Chen](https://miro.medium.com/v2/da:true/resize:fill:32:32/0*24nFS0OxJH6QzsaL)](https://medium.com/@kiancaca?source=post_page---byline--669fbc67342c---------------------------------------)

[Chiahui Chen](https://medium.com/@kiancaca?source=post_page---byline--669fbc67342c---------------------------------------)

Follow

1 hour ago

[](https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fvote%2Fp%2F669fbc67342c&operation=register&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&user=Chiahui+Chen&userId=9566120b15e1&source=---header_actions--669fbc67342c---------------------clap_footer------------------)

[](https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fbookmark%2Fp%2F669fbc67342c&operation=register&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&source=---header_actions--669fbc67342c---------------------bookmark_footer------------------)

Share

Press enter or click to view image in full size

![Image 3: bfs traversal figure](https://miro.medium.com/v2/resize:fit:700/1*Zi2HZFxfmEZBWTs6gbxbbA.png)

bfs 像是一個同心圓,從圓心開始同步向外擴散。

## Get Chiahui Chen’s stories in your inbox

Join Medium for free to get updates from this writer.

Subscribe

Subscribe

- [x]

Remember me for faster sign in



同步的意思是,從圓心走到同半徑距離點的步數一樣。

from collections import deque

MOVE = [(-1, 0), (0, 1), (1, 0), (0, -1)]

q = deque()

visited = set()

m, n = map(int, input().split())

mat = [[int(x) for x in input().split()] for _ in range(m)]

r, c = map(int, input().split())

origin = (r, c)

q.append(origin)

visited.add(origin)

while q:

r, c = q.popleft()

print(r, c)



for dr, dc in MOVE:

rr, cc = r + dr, c + dc

if rr < 0 or cc < 0 or rr >= m or cc >= n or (rr, cc) in visited:

continue

visited.add((rr, cc))

q.append((rr, cc))

[Data Structure Algorithm](https://medium.com/tag/data-structure-algorithm?source=post_page-----669fbc67342c---------------------------------------)

[Python](https://medium.com/tag/python?source=post_page-----669fbc67342c---------------------------------------)

[](https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fvote%2Fp%2F669fbc67342c&operation=register&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&user=Chiahui+Chen&userId=9566120b15e1&source=---footer_actions--669fbc67342c---------------------clap_footer------------------)

[](https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fvote%2Fp%2F669fbc67342c&operation=register&redirect=https%3A%2F%2Fmedium.com%2F%40kiancaca%2Fbfs-669fbc67342c&user=Chiahui+Chen&userId=95
Read full article → ← Back to Reads