DFS - DFS와BFS[1260번]
2022. 4. 17. 00:00ㆍ2022/BaekJoon_알고리즘
def DFS(loc):
visited.append(loc)
for idx in range(1, len(graph[loc])):
if len(visited) == n:
return
elif graph[loc][idx] == 1 and idx not in visited:
loc = idx
DFS(loc)
def BFS(loc):
queue = [loc]
visited2.append(loc)
while queue:
curCheck = queue.pop(0)
for idx in range(1, len(graph[curCheck])):
if len(visited2) == n:
return
elif graph[curCheck][idx] == 1 and (idx not in visited2) and (idx not in queue):
queue.append(idx)
visited2.append(idx)
n, m, startN = map(int, input().split())
graph = [[0]*(n+1) for _ in range(n+1)]
for i in range(m):
node1, node2 = map(int, input().split())
graph[node1][node2] = 1
graph[node2][node1] = 1
global visited
global visited2
visited = []
visited2 = []
DFS(startN)
print(visited)
BFS(startN)
print(visited2)
'2022 > BaekJoon_알고리즘' 카테고리의 다른 글
BFS - 미로 탐색 [2178번] (0) | 2022.07.14 |
---|---|
DFS - 연결 요소의 개수[11724번] (0) | 2022.04.18 |
DFS - 바이러스[2606번] (0) | 2022.04.09 |
Dynamic Programming(DP) - 정수 삼각형[1932] (0) | 2022.04.07 |
Dynamic Programming(DP) - RGB거리[1149] (0) | 2022.04.06 |