-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS와 BFS.py
More file actions
46 lines (34 loc) · 898 Bytes
/
DFS와 BFS.py
File metadata and controls
46 lines (34 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import sys
from collections import deque
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
n, m, start = map(int, input().split())
graph = [[] for _ in range(n + 1)]
visited_dfs = [False] * (n + 1)
visited_bfs = [False] * (n + 1)
for _ in range(m):
s, e = map(int, input().split())
graph[s].append(e)
graph[e].append(s)
for i in range(n + 1):
graph[i].sort()
def DFS(v):
visited_dfs[v] = True
print(v, end = " ")
for i in graph[v]:
if not visited_dfs[i]:
DFS(i)
DFS(start)
def BFS(v):
visited_bfs[v] = True
queue = deque()
queue.append(v)
while queue:
curr = queue.popleft()
print(curr, end = " ")
for i in graph[curr]:
if not visited_bfs[i]:
queue.append(i)
visited_bfs[i] = True
print()
BFS(start)