https://www.acmicpc.net/problem/1172
from collections import deque
import sys
N, Mmap(int, sys.stdin.readline().split())
graph= [[] for _in range(N+1)]
for i in range(M):
a, bmap(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
visited= [False]*(N+1)
def bfs(graph, startn, visited):
queuedeque([startn])
visited[startn] = True
while queue:
curqueue.popleft()
for i in graph[cur]:
if not visited[i]:
queue.append(i)
visited[i] = True
a=0
for i in range(1, N+1):
if visited[i]:
continue
bfs(graph, i, visited)
a+= 1
print(a)
from collections import deque
import sys
limit_number = 15000
sys.setrecursionlimit(limit_number)
N, M = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(N+1)]
for i in range(M):
a, b = map(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
visited = [False]*(N+1)
def dfs(graph, startn, visited):
visited[startn] = True
for i in graph[startn]:
if not visited[i]:
dfs(graph, i, visited)
a = 0
for i in range(1, N+1):
if visited[i]:
continue
dfs(graph, i, visited)
a += 1
print(a)
from collections import deque
import sys
N, Mmap(int, sys.stdin.readline().split())
########################################################
graph= {}
for i in range(N):
graph[i+1] = []
########################################################
for i in range(M):
a, bmap(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
visited= [False]*(N+1)
a=0
def bfs(graph, startn, visited):
# global a
b=0
queuedeque([startn])
visited[startn] = True
while queue:
curqueue.popleft()
for i in graph[cur]:
if not visited[i]:
queue.append(i)
visited[i] = True
b=1
if b== 1:
a+= 1
for i in range(1, N+1):
if visited[i]:
continue
bfs(graph, i, visited)
print(a)
내가 처음에 작성한 코드
1) 인접리스트를 오랜만에 풀어보아서 그런지 나는 딕셔너리 형태가 편했다.
리스트를 이용해서 0인덱스를 비워두고 1~N 인덱스도 표현할 수 있었다
graph = [ [] for_in range(N+1) ]
2) 전역변수 사용은 최소화 해야겠다. 백준에서는 오류가 뜬다.