DFS BFS 알아둘 것
- DFS 문제든 BFS 문제든 방문 기록을 활용하는 방식으로,
- "방문 기록"을 남기는 방향으로 문제를 푸는 유형이다 라고 생각하면 될거같다.
Python - Stack & Queue
- Stack 사용 시 그냥 list를 활용
- stack = []
- stack.append(4)
- stack.pop() # 최상단 원소 제거
- Queue 사용 시 라이브러리 활용 <중요>
- from collections import deque
- queue = deque() # 큐 생성
- queue.append(5)
- queue.popleft() # 가장 먼저 들어온 데이터 삭제
- queue.reverse() # 큐 내용물을 역순으로 바꾸기

""" Python """
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)

''' 내가 짠 코드 '''
def dfs(graph, v, visited):
if visited[v] == False:
visited[v] = True
print(v, end=' ')
for i in graph[v]:
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 핵심
0. BFS는 재귀 X이다.
1. 따라서 BFS 안에 큐 생성한다
2. 시작 포인트 일단 넣는다
3. while queue
4. 현위치 = popleft()
5. for 다음위치(또는 다음 노드) 가져와
6. 다음 위치가 조건에 맞으면(또는 방문 안했으면) 이동시켜
7. queue.append(다음위치) <--- 개중요 (for안에 넣어서 다음위치/이웃노드 전부 넣어주는)
- 그리고 DFS 문제든 BFS 문제든 방문 기록을 활용하는 방식으로,
- "방문 기록"을 남기는 방향으로 문제를 푸는 유형이다 라고 생각하면 될거같다.
''' Python '''
from collections import deque
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
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)

''' 내가 짠 코드 '''
from collections import deque
queue = deque()
def bfs(graph, v, visited):
if visited[v] == False:
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if visited[i] == False:
queue.append(i)
if len(queue) > 0:
bfs(graph, queue.popleft(), visited)
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)

- 그래프 만들기 (중요)
- 입력은 그래프 형태로 줄 수도 있지만, edge형태로 준다면 graph로 변환해야 함

''' 내가 만든 - 밑에거가 더 편하다 '''
n, m, v = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(m)]
check = [False] * (n+1)
graph = [[] for _ in range(n+1)]
for i in range(len(arr)):
graph[arr[i][0]].append(arr[i][1])
graph[arr[i][1]].append(arr[i][0])
print(graph)

''' 다른 사람 코드 (블로그) '''
import sys
input=sys.stdin.readline
n,m,start=map(int,input().split())
visited=[False]*(n+1)
graph=[[] for _ in range(n+1)]
for _ in range(m):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)