https://www.acmicpc.net/problem/11724
import sys
input = sys.stdin.readline
#3.함수 정의
def bfs(node):
queue=[node]
while queue:
curr_node=queue.pop(0)
visited[curr_node]=True
for next_node in graph[curr_node]:
if not visited[next_node]:
queue.append(next_node)
visited[next_node]=True
#1.입력받기
N,M=map(int,input().split()) #N:정점/M:간선
graph=[[] for _ in range(N+1)]
for _ in range(M):
u,v=map(int,input().split())
graph[u].append(v)
graph[v].append(u)
visited=[False for _ in range(N+1)]
#2.자료형 정의
#4.출력
cnt=0
for i in range(1,N+1):
if not visited[i]:
bfs(i)
cnt+=1
print(cnt)
간선들의 입력에 대한 matrix 배열을 만드는게 아닌 간선들이 연결된 정점들만 저장하여 그래프를 구성하면 훨씬 더 간단해진다.
'coding test > Baekjoon' 카테고리의 다른 글
| [Python] 1991번 트리 순회 (0) | 2025.05.08 |
|---|---|
| [Python] 24444번 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2025.04.23 |
| [Python] 2667번 단지번호붙이기 (0) | 2025.04.23 |
| [Python] 2210번 숫자판 점프 (0) | 2025.04.13 |
| [Python] 4963번 섬의 개수 / DFS.ver (0) | 2025.04.13 |