HACKERRANK/CODE
[HACKERRANK] - BFS: Shortest Reach in a Graph
나른한 사람
2021. 2. 7. 10:03
www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem
BFS: Shortest Reach in a Graph | HackerRank
Implement a Breadth First Search (BFS).
www.hackerrank.com
BFS 문제.
<My Solution>
from collections import deque
class Graph:
def __init__(self,n):
self.n = n
self.nodes = {i:[] for i in range(n)}
def connect(self,a,b):
self.nodes[a].append(b)
self.nodes[b].append(a)
def find_all_distances(self,s):
depths = [-1 for _ in range(self.n)]
q = deque([[s,0]])
visited = set({s})
while q:
num, depth = q.popleft()
for x in self.nodes[num]:
if x not in visited:
q.append([x,depth+6])
visited.add(x)
depths[x] = depth+6
print(*(depths[:s]+depths[s+1:]))