Skip to content

Instantly share code, notes, and snippets.

@ssabii
Created September 21, 2020 10:49
Show Gist options
  • Save ssabii/0bf12e28c98e1957985903dc34b17d1c to your computer and use it in GitHub Desktop.
Save ssabii/0bf12e28c98e1957985903dc34b17d1c to your computer and use it in GitHub Desktop.
그래프 BFS
from collections import deque
def bfs(vertex, graph):
visited = set()
queue = deque()
visited.add(vertex)
queue.append(vertex)
while len(queue) > 0:
curr_v = queue.popleft()
print(curr_v + 1, end=" -> ") # 출력용
for i, v in enumerate(graph[curr_v]):
if v == 1 and i not in visited:
visited.add(i)
queue.append(i)
if __name__ == "__main__":
graph = [
[0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0]
]
bfs(0, graph)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment