반응형
https://www.hackerrank.com/challenges/find-the-nearest-clone/problem
Find the nearest clone | HackerRank
Find the shortest path length between any two nodes with the given condition.
www.hackerrank.com


constraint 값이 꽤 커 보여서, 2D Array로 그래프를 구성하는 대신 defaultdict를 사용했다.
bfs로 그래프를 순회하면서, 시작점의 color와 순회지점의 color가 일치하는 지점에서 순회 횟수를 반환하면 된다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import math | |
import os | |
import random | |
import re | |
import sys | |
from collections import deque, defaultdict | |
# Complete the findShortest function below. | |
# | |
# For the weighted graph, <name>: | |
# | |
# 1. The number of nodes is <name>_nodes. | |
# 2. The number of edges is <name>_edges. | |
# 3. An edge exists between <name>_from[i] to <name>_to[i]. | |
# | |
# | |
def findShortest(graph_nodes, graph_from, graph_to, ids, val): | |
# solve here | |
# try: | |
maps = defaultdict(list) | |
# maps = [[0 for _ in range(graph_nodes+1)] for _ in range(graph_nodes+1)] | |
print(maps) | |
color = defaultdict(int) | |
for i in range(len(graph_from)): | |
maps[graph_from[i]].append(graph_to[i]) | |
maps[graph_to[i]].append(graph_from[i]) | |
if graph_from[i] not in color: | |
color[graph_from[i]] = ids[graph_from[i]-1] | |
if graph_to[i] not in color: | |
color[graph_to[i]] = ids[graph_to[i]-1] | |
queue = deque() | |
queue.append((val, 0)) | |
start_color = color[val] | |
visited = set() | |
while queue: | |
current, cnt = queue.popleft() | |
visited.add(current) | |
for x in maps[current]: | |
if x not in visited: | |
if color[x] == start_color: | |
return cnt + 1 | |
visited.add(x) | |
queue.append((x, cnt+1)) | |
return -1 | |
if __name__ == '__main__': | |
fptr = open(os.environ['OUTPUT_PATH'], 'w') | |
graph_nodes, graph_edges = map(int, input().split()) | |
graph_from = [0] * graph_edges | |
graph_to = [0] * graph_edges | |
for i in range(graph_edges): | |
graph_from[i], graph_to[i] = map(int, input().split()) | |
ids = list(map(int, input().rstrip().split())) | |
val = int(input()) | |
ans = findShortest(graph_nodes, graph_from, graph_to, ids, val) | |
fptr.write(str(ans) + '\n') | |
fptr.close() |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] Hackerrank. Sherlock and the Valid String (Medium) (0) | 2020.03.11 |
---|---|
[Python] Hackerrank. Big Sorting (Easy) (0) | 2020.03.10 |
[Python] 프로그래머스. 2018 카카오 recruit - 프렌즈4블록 (Level 2) (0) | 2020.03.07 |
[Python] 백준 1890. 점프 (0) | 2020.03.05 |
[Python] 백준 14500. 테트로미노 (0) | 2020.03.04 |