https://www.acmicpc.net/problem/11724
11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주
www.acmicpc.net
Solution. 1
from collections import deque
import sys
input = sys.stdin.readline # 시간 초과 해결
n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
x,y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
def bfs(x,y):
queue = deque()
queue.append([x,y])
while queue:
nx, ny = queue.popleft()
if graph[nx] != []:
for i in graph[nx]:
queue.append([nx,i])
graph[nx].remove(i)
if graph[ny] != []:
for j in graph[ny]:
queue.append([ny,j])
graph[ny].remove(j)
return graph
cnt = 0
for i in range(n):
if graph[i+1] != []:
graph = bfs(i+1,graph[i+1][0])
cnt+=1
print(cnt)
시간 초과가 나왔다.
import sys
input = sys.stdin.readline
input 단계에서 시간 초과가 이미 발생하는 것이었다.
sys.stdin.readline을 통해 해결가능했다.
Solution. 2
from collections import deque
import sys
input = sys.stdin.readline # 없으면 시간 초과 발생
n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
visited = [False]*(n+1)
for _ in range(m):
x,y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
while queue:
n = queue.popleft()
for i in graph[n]:
if visited[i] == False: # 미방문 노드일 경우
queue.append(i)
visited[i] = True
cnt = 0
for i in range(1,n+1):
if visited[i] == False: # 미방문 노드일 경우
bfs(graph, i, visited)
cnt+=1
print(cnt)
visited를 사용하여 더 빠르고 간단하게 구현할 수 있었다.
'Programming > DFSBFS' 카테고리의 다른 글
Programmers / 단어 변환 (0) | 2022.04.29 |
---|---|
Baekjoon / BFS / 음식물피하기 (0) | 2022.03.25 |
Baekjoon / DFS / 유기농 배추 (0) | 2022.02.13 |
Baekjoon / BFS / 미로탐색 (0) | 2022.02.11 |
Programmers / BFS / 네트워크 (0) | 2022.01.22 |