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 |
Tags
- parklab
- likelionlikelion
- 프로젝트
- ux·ui디자인
- Join
- tog
- graphrag
- 인턴10
- BFS
- 시각화
- 마이온
- paper review
- 알고리즘
- GNN
- TiL
- DP
- DFS
- 파이썬
- folium
- 멋사
- 멋쟁이사자처럼
- seaborn
- likelion
- intern10
- SQL
- Rag
- 멋재이사자처럼
- Python
- 마이온컴퍼니
- 그리디
Archives
- Today
- Total
지금은마라톤중
[백준] 2644번 촌수계산 본문
접근법
- 2명 사이의 촌수를 계산해야하니 DFS로 접근
- 촌수를 계산할 수 없을 때 -1 출력해야하니 check 변수 사용
from collections import deque
n = int(input())
a,b = map(int,input().split())
num = int(input())
check = False
graph = [[] for _ in range(n+1)]
visited = [0] *(n+1)
for _ in range(num):
x,y = map(int,input().split())
graph[x].append(y)
graph[y].append(x)
def dfs(graph, c, visited, cnt):
visited[c] = 1
global check
if c == b :
check = True
print(cnt)
for i in graph[c]:
if visited[i] == 0 :
dfs(graph, i, visited, cnt+1)
dfs(graph,a,visited, 0)
if check == False :
print(-1)
'STUDY > Python 알고리즘' 카테고리의 다른 글
[백준] 111724번 연결 요소의 개수 (0) | 2024.04.02 |
---|---|
[백준] 2667번 단지번호붙이기 (1) | 2024.03.27 |
[백준] 1012번 유기농배추 (0) | 2024.03.25 |
[백준] 1260번 DFS와 BFS (1) | 2024.03.22 |
[백준] 1764번 듣보잡 / set() 집합의 시간복잡도 (1) | 2024.02.27 |
Comments