티스토리 뷰

728x90

www.acmicpc.net/problem/1260

소스코드

def dfs(x):
    print(x, end = " ")
    visit[x] = 1
    for i in range(1, n+1):
        if s[i][x] == 1 and visit[i] == 0:
            dfs(i)


def bfs(v):
    que = []
    que.append(v)

    while que:
        x = que.pop(0)
        visit[v] = 0
        print(x, end = ' ')
        for i in range(1, n+1):
            if s[x][i] == 1 and visit[i] == 1:
                que.append(i)
                visit[i] = 0
            

n, m, v = map(int, input().split())
s = [[0]*(n+1) for i in range(n+1)]


for i in range(m):
    x, y = map(int, input().split())
    s[x][y] = s[y][x] = 1

visit = [0 for i in range(n+1)]
dfs(v)
print()
bfs(v)
반응형