[알고리즘개념] DFS/BFS

Dana·2021년 5월 24일
0

알고리즘

목록 보기
8/8

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)

visited = [False] * 9
dfs(graph, 1, visited)
graph = [[0] * (n+1) for i in range(n+1)]
visited = [False] * (n+1)

def dfs(v):
    visited1[v] = True
    print(v, end=' ')
    for i in range(1, n+1):
        if not visited1[i] and graph[v][i] == 1:
            dfs(i)

BFS - 너비 우선 탐색

from collections import deque

def bfs(graph, start, visited):
	queue = deque([start])
    visited[start] = True
    while queue:
    	v = queue.popleft()
        for i in graph[v]:
        	if not visited[i]:
            	queue.append(i)
                visited[i] = True
                
visited = [False] * 9
bfs(graph, 1, visited)
graph = [[0] * (n+1) for i in range(n+1)]
visited = [False] * (n+1)

def bfs(v):
    queue = deque([v])
    visited2[v] = True
    while queue:
        v = queue.popleft()
        print(v, end=' ')
        for i in range(1, n+1):
            if not visited2[i] and graph[v][i] == 1:
                queue.append(i)
                visited2[i] = True

0개의 댓글