본문 바로가기
Programming Test/문제풀이

[문제 풀이 17] 코드 트리 - 연결된 그래프

by muns91 2024. 4. 18.
연결된 그래프

 

  • 문제 유형 : DFS
  • 사용언어 : Python
  • 난이도 : 실버 3
  • 출처 : 코드 트리

https://www.codetree.ai/training-field/search/problems/connected-graph?&utm_source=clipboard&utm_medium=text

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

n, m = tuple(map(int, input().split()))
graph = [[] for _ in range(n+1)]

check = [False for _ in range(n+1)]

vex_cnt =0

for _ in range(m):
    v1, v2 = tuple(map(int, input().split()))
    graph[v1].append(v2)
    graph[v2].append(v1)

#print(graph)

def dfs(vex):
    global vex_cnt

    for x in graph[vex]:

        if not check[x]:
            check[x] = True
            vex_cnt +=1
            dfs(x)



vex = 1
check[vex] = True
dfs(vex)
print(vex_cnt)