데이터사이언스 기록기📚

[백준/Python] 2644번(그래프이론, 그래프탐색, DFS,BFS)_촌수계산 본문

Coding Test/백준(Python)

[백준/Python] 2644번(그래프이론, 그래프탐색, DFS,BFS)_촌수계산

syunze 2023. 4. 14. 20:47

📌문제 유형

그래프이론, 그래프탐색, 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
Comments