반응형
[Graph] DFS(Depth first Search), 깊이우선탐색에서는 stack을 이용하고,
BFS에서는 queue를 이용하면 된다.
vertextList = [0, 1, 2, 3, 4, 5, 6]
edgeList = [(0, 1), (1, 0), (0, 2), (2, 0), (1, 3), (3, 1),
(2, 4), (4, 2), (2, 5), (5, 2), (4, 6), (6, 4)]
graphs = (vertextList, edgeList)
def bfs(graph, start):
vertextList, edgeList = graph
visitedVertex = []
queue = [start]
adjacencyList = [[] for vertex in vertextList]
for edge in edgeList:
adjacencyList[edge[0]].append(edge[1])
while queue:
current = queue.pop()
for neighbor in adjacencyList[current]:
if neighbor not in visitedVertex:
queue.insert(0, neighbor)
visitedVertex.append(current)
return visitedVertex
print(bfs(graphs, 0))
* list.insert(index, value): 원하는 인덱스에 값 넣기
반응형
'Data > python·알고리즘' 카테고리의 다른 글
[Graph] 최단경로검색, Dijkstra algorithm(다익스트라) (2) | 2018.09.25 |
---|---|
[Graph] DFS(Depth First Search), 깊이우선탐색 (0) | 2018.09.24 |
[Binary Tree] 이진트리(2) - pre order, in order, post order (0) | 2018.09.24 |
[Binary Tree] 이진트리 (1) - 삽입, 삭제 (0) | 2018.09.24 |
[heap sort] 힙 힙 힙! (0) | 2018.09.24 |
댓글