스택
stack = [] stack.append(5) # [5] stack.append(2) # [5, 2] stack.append(3) # [5, 2, 3] stack.append(7) # [5, 2, 3, 7] stack.pop() # [5, 2, 3] stack.append(1) # [5, 2, 3, 1] stack.append(4) # [5, 2, 3, 1, 4] stack.pop() # [5, 2, 3, 1] print(stack[::-1]) # 최상단부터 출력 -> [1, 3, 2, 5] print(stack) # 최하단부터 출력 -> [5, 2, 3, 1]
큐
from collections import deque queue = deque() queue.append(5) # [5] queue.append(2) # [5, 2] queue.append(3) # [5, 2, 3] queue.append(7) # [5, 2, 3, 7] queue.popleft() # [2, 3, 7] queue.append(1) # [2, 3, 7, 1] queue.append(4) # [2, 3, 7, 1, 4] queue.popleft() # [3, 7, 1, 4] print(queue) # [3, 7, 1, 4] queue.reverse() print(queue) # [4, 1, 7, 3]
DFS
(방문 -> 방문 안 한 이웃 확인 -> 반복)
def dfs(graph, v, visited): visited[v] = True print(v, end=' ') for i in graph[v]: if not visited[i]: dfs(graph, i, visited) graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [False] * 9 dfs(graph, 1, visited)
BFS
(방문<큐에서 빼기> -> 방문 안 한 이웃 큐에 넣기 -> 반복)
from collections import deque def bfs(graph, start, visited): visited[start] = True queue = deque([start]) while queue: v = queue.popleft() print(v, end = ' ') for i in graph[v]: if not visited[i]: queue.append(i) visited[i] = True graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [False] * 9 bfs(graph, 1, visited)
이진 탐색
다익스트라 알고리즘
플로이드-워셜 알고리즘
크루스칼 알고리즘
위상정렬 알고리즘