Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- geopy
- 그래프탐색
- xmltodict
- cosine
- dp
- 비트마스킹
- 건축물대장정보
- TF-IDF
- 코사인유사도
- Geocoding
- 그리디
- 백준
- 공공데이터
- 유클리드
- 지진대피소
- pandas
- 그래프이론
- 자연어처리
- 우선순위큐
- 너비우선탐색
- 누적합
- 유사도
- 깊이우선탐색
- GroupBy
- NLP
- 분할정복
- 수학
- 구현
- 전처리
- 재귀
Archives
- Today
- Total
정리용
[백준 11724] 파이썬 - 연결 요소의 개수 본문
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
1. 코드설명
1-1 재귀
sys.setrecursionlimit(10**6)
def dfs(i):
done[i]=1
for j in arr[i]:
if done[j]==0:
dfs(j)
n,m =map(int,input().split())
arr = [[] for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
arr[a].append(b)
arr[b].append(a)
cnt = 0
done=[0]*(n+1)
for i in range(1,n+1):
if done[i]==0:
dfs(i)
cnt+=1
print(cnt)
1-2
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
dic = {i : [] for i in range(1, N+1)}
for _ in range(M):
a, b = map(int, input().split())
dic[a].append(b)
dic[b].append(a)
visited = [0] * (N + 1)
ans = 0
for i in range(1, N+1):
if visited[i] == 1 : continue
else :
visited[i] = 1
ans += 1
to_do = [i]
while to_do :
x = to_do.pop()
for y in dic[x]:
if visited[y] == 0:
visited[y] = 1
to_do.append(y)
print(ans)
2. 주의사항
재귀의 경우
sys.setrecursionlimit(10**6) 으로 반복의 깊이를 지정해 주지 않으면 오류가 발생한다.
'알고리즘 > 백준' 카테고리의 다른 글
1 (0) | 2022.02.07 |
---|---|
[백준 11723] 파이썬 - 집합 (0) | 2022.01.11 |
[백준 11659] 파이썬 - 구간합 구하기 4 (0) | 2022.01.10 |
[백준 11047] 파이썬 - 동전 0 (산술 연산자) (0) | 2022.01.06 |
[백준 9095] 파이썬 - 1,2,3 더하기 (0) | 2022.01.03 |
Comments