DFS - DFS와BFS[1260번]

2022. 4. 17. 00:002022/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)