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:]))
'HACKERRANK > CODE' 카테고리의 다른 글
[HACKERRANK] - DFS: Connected Cell in a Grid (0) | 2021.02.07 |
---|---|
[HACKERRANK] - Find the nearest clone (1) | 2021.02.06 |
[HACKERRANK] - Roads and Libraries (0) | 2021.02.04 |
[HACKERRANK] - Recursive Digit Sum (0) | 2021.02.04 |
[HACKERRANK] - Crossword Puzzle (0) | 2021.02.04 |
댓글