Created
April 6, 2020 02:06
-
-
Save nhudinhtuan/bbf7cd517000b45c6079a9f3e31d6919 to your computer and use it in GitHub Desktop.
BFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
# graph: List[List[int]] | |
# s: start vertex | |
def bfs(graph, s): | |
# set is used to mark visited vertices | |
visited = set() | |
# create a queue for BFS | |
queue = deque() | |
# Mark the start vertex as visited and enqueue it | |
visited.add(s) | |
queue.appendleft(s) | |
while queue: | |
current_vertex = queue.pop() | |
print(current_vertex) | |
# Get all adjacent vertices of current_vertex | |
# If a adjacent has not been visited, then mark it | |
# visited and enqueue it | |
for v in graph[current_vertex]: | |
if v not in visited: | |
visited.add(v) | |
queue.appendleft(v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment