We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
fromcollectionsimportdefaultdict,dequedefbfs(n,m,edges,s):# direct connections of nodeconct=defaultdict(list)fornode1,node2inedges:conct[node1].append(node2)conct[node2].append(node1)# store distance to each node (default: -1)dist={i:-1foriinrange(1,n+1)}dist[s]=0dist_unit=6# create a deque (double-ended queue) to process traversing nodesdq=deque([s])# traversing process (perform BFS)whiledq:curr_node=dq.popleft()distance=dist[curr_node]+dist_unit#distancebetweensandnextnodefornext_nodeinconct[curr_node]:ifdist[next_node]==-1:dist[next_node]=distancedq.append(next_node)return[dist[i]foriinrange(1,n+1)ifi!=s]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Breadth First Search: Shortest Reach
You are viewing a single comment's thread. Return to all comments →