Study/코딩테스트 연습
프로그래머스 dfs bfs 여행경로
soyeonland
2024. 10. 13. 21:28
문제
잘못한 풀이
더보기
from collections import deque
#1. 같은 항공권이 중복될 수 있음
#2. 모든 도시를 방문할 수 없는 알고리즘?
def solution(tickets):
answer = []
graph = []
visited = []
all_dict = {}
all_dict_revers = {}
#print("a"<"b")
def make_graph():
nonlocal graph, all_dict, visited, all_dict_revers
all = []
for start, end in tickets:
all.append(start)
all.append(end)
all = set(all)
all = list(all)
all = sorted(all)
for idx, city in enumerate(all):
all_dict[city] = idx
for city, idx in all_dict.items():
all_dict_revers[idx] = city
all_len = len(all)
graph = [[0]*(all_len) for _ in range(all_len)]
visited = [[0]*(all_len) for _ in range(all_len)]
for start, end in tickets:
start_num = all_dict[start]
end_num = all_dict[end]
graph[start_num][end_num] = 1
def bfs():
nonlocal answer
q = deque()
q.append("ICN")
while(len(q)>=1):
cur_city = q.popleft()
cur_num = all_dict[cur_city]
answer.append(cur_city)
for next_num in range(len(graph[cur_num])):
if graph[cur_num][next_num]==0:
continue
if visited[cur_num][next_num]==1:
continue
next_city = all_dict_revers[next_num]
visited[cur_num][next_num] = 1
q.append(next_city)
break
make_graph()
bfs()
# for start, end in tickets:
#print('graph',graph, 'all_dict',all_dict, "all_dict reverse", all_dict_revers)
return answer