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 |
Tags
- 브라이틱스 서포터즈
- 직원 이직여부
- 삼성SDS Brightics
- 캐글
- Brightics
- 포스코 청년
- 삼성SDS Brigthics
- 혼공
- 데이터 분석
- 모델링
- 추천시스템
- 노코드AI
- 혼공머신
- 브라이틱스
- 데이터분석
- 개인 의료비 예측
- Brightics를 이용한 분석
- 직원 이직률
- Brigthics Studio
- 혼공머신러닝딥러닝
- Brigthics를 이용한 분석
- 영상제작기
- 삼성 SDS
- 혼공학습단
- 포스코 아카데미
- 삼성SDS
- Brightics Studio
- 팀 분석
- 삼성 SDS Brigthics
- Brigthics
Archives
- Today
- Total
데이터사이언스 기록기📚
[백준/Python] 2644번(그래프이론, 그래프탐색, DFS,BFS)_촌수계산 본문
📌문제 유형
그래프이론, 그래프탐색, DFS, BFS (실버2)
📌문제
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
📌나의 문제풀이
- 실패
n = int(input())
a, b = map(int,input().split())
m = int(input())
def find_parent(parent, x):
if parent[x] != x:
return find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a,b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
# 여기만 수정해보기
def cnt_degree(graph,a,b,ans):
if a in graph[b]:
return ans
for num in graph[b]:
if b not in graph[num]:
ans += 1
cnt_degree(graph,a,graph[num])
parent = [i for i in range(n+1)]
graph = [[] for i in range(n+1)]
for _ in range(m):
x,y = map(int,input().split())
union_parent(parent, x,y)
graph[x].append(y)
graph[y].append(x)
print(graph)
if parent[a] != parent[b]:
print(-1)
else:
print(cnt_degree(graph,a,b,0)) # 자식에서 타고 올라가기
📌 다른사람의 문제풀이
[백준 python] 2644번 촌수계산 DFS - 파이썬
[백준 python] 2644번 촌수 계산 DFS 레벨: 실버2 언어: 파이썬 문제풀러가기 2644번: 촌수계산 사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람
wonyoung2257.tistory.com
[파이썬] 2644번 '촌수계산' 문제 풀이
예가 다음과 같이 나오는 경우 9 7 3 7 1 2 1 3 2 7 2 8 2 9 4 5 4 6 인접 리스트는 [[], [2, 3], [1, 7, 8, 9], [1], [5, 6], [4], [4], [2], [2], [2]]로 표현되며, 자식을 트리의 시작노드, 부모를 자식노드로 놓고 순회하
lbdiaryl.tistory.com
# 입력값 받는 부분
N = int(input())
A, B = map(int, input().split())
M = int(input())
graph = [[] for _ in range(N+1)]
visited = [False] * (N+1)
result = []
####
# 어떤 노드들이 연결되어 있는지 graph라는 2차원 배열에 저장
for _ in range(M):
x, y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
# dfs
def dfs(v, num):
num += 1
visited[v] = True
if v == B:
result.append(num)
for i in graph[v]:
if not visited[i]:
dfs(i, num)
dfs(A, 0)
if len(result) == 0:
print(-1)
else:
print(result[0]-1)
# DFS
def dfs(v):
visited[v] = True
for i in graph[v]:
if not visited[i]:
res[i] = res[v] + 1
dfs(i)
n=int(input())
A,B=map(int,input().split())
m=int(input())
graph=[[] for _ in range(n+1)]
visited = [False] * (n + 1)
res=[0]*(n+1)
for _ in range(m):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
dfs(A)
if res[B]>0:
print(res[B])
else:
print(-1)
# BFS
from collections import deque
def bfs(s):
queue=deque([s])
visited[s]=True
while queue:
v=queue.popleft()
for i in graph[v]:
if not visited[i]:
queue.append(i)
res[i]=res[v]+1
visited[i]=True
n=int(input())
A,B=map(int,input().split())
m=int(input())
graph=[[] for _ in range(n+1)]
visited = [False] * (n + 1)
res=[0]*(n+1)
for _ in range(m):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
bfs(A)
if res[B]>0:
print(res[B])
else:
print(-1)
📌 리뷰
- DFS 확인할 때, 겹치지 않도록 노드 방문 여부도 체크하기
728x90
'Coding Test > 백준(Python)' 카테고리의 다른 글
[백준/Python] 1758번(그리디, 정렬)_알바생 강호 (0) | 2023.04.15 |
---|---|
[백준/Python] 11724번(그래프이론, 그래프탐색, DFS, BFS)_연결 요소의 개수 (0) | 2023.04.15 |
[백준/Python] 9017번(구현)_ 크로스 컨트리 (0) | 2023.04.13 |
[백준/Python] 1436번(브루트포스 알고리즘(완탐))_영화감독 숌 (0) | 2023.04.12 |
[백준/Python] 10431번(구현, 시뮬레이션)_줄세우기 (0) | 2023.04.12 |
Comments