728x90
반응형

 

1. 시간 초과 코드 

# 2644

n = int(input()) # 전체 사람의 수 
a, b = map(int,input().split())
m = int(input()) # 관계의 수 

graph = [ [] for _ in range(n+1) ] 

for i in range(m):
  p, c = map(int,input().split())
  graph[p].append(c)

def bfs(x, y):
  p ,cnt = 0, 1

  while 1: 
    for i in range(1,n+1):
      if x in graph[i]:
        p = i 
        break 
    
    if p == 0 : return -1 
    else : cnt += 1 
    
    if y in graph[p] : return cnt 
    else : x = p  

print( bfs(a,b) ) 

 

2. 정답 코드 

# 2644
from collections import deque 

n = int(input()) # 전체 사람의 수 
a, b = map(int,input().split())
m = int(input()) # 관계의 수 

graph = [ [] for _ in range(n+1) ] 

for i in range(m):
  p, c = map(int,input().split())
  graph[p].append(c)
  graph[c].append(p)


def bfs(s, e):
  cnt = 0 
  queue = deque()
  queue.append(s) 
  visited = [False] * (n+1)  # 한 번 방문했는데 없던 곳 또 가지 않는다. 

  while queue:
    cnt += 1  # 한 단계 건널 때 마다 촌수 추가 
    
    for _ in range(len(queue)): # 지금 queue의 원소 만큼 반복 
      x = queue.popleft()

      if x == e : 
        return cnt-1
      
      for y in graph[x]:
        # 방문 안한 부분이 있으면 queue에 넣고 방문처리 
        if visited[y] == False:
          visited[y] = True 
          queue.append(y)
  
  return -1 

print( bfs(a,b) ) 
728x90
반응형

'백준 > DFS_BFS' 카테고리의 다른 글

#1743 음식물 피하기 파이썬  (0) 2021.04.08
# 11725 트리의 부모 찾기 파이썬  (0) 2021.03.11
# 2583번: 영역 구하기  (0) 2020.10.12
# 2468번: 안전 영역  (0) 2020.10.12
# 4963번: 섬의 개수  (0) 2020.10.12

+ Recent posts