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.
packagemainimport("container/heap""math")typeEdgestruct{toint32weightint32}typeItemstruct{nodeint32distint32}typeMinHeap[]Itemfunc(hMinHeap)Len()int{returnlen(h)}func(hMinHeap)Less(i,jint)bool{returnh[i].dist<h[j].dist}func(hMinHeap)Swap(i,jint){h[i],h[j]=h[j],h[i]}func(h*MinHeap)Push(xinterface{}){*h=append(*h,x.(Item))}func(h*MinHeap)Pop()interface{}{old:=*hn:=len(old)item:=old[n-1]*h=old[:n-1]returnitem}funcshortestReach(nint32,edges[][]int32,sint32)[]int32{graph:=make(map[int32][]Edge)// Use only smallest edge if multiple exist between two nodesminEdge:=make(map[[2]int32]int32)for_,edge:=rangeedges{u,v,w:=edge[0],edge[1],edge[2]key1:=[2]int32{u,v}key2:=[2]int32{v,u}ifval,ok:=minEdge[key1];!ok||w<val{minEdge[key1]=wminEdge[key2]=w}}// Build the graphforkey,w:=rangeminEdge{u,v:=key[0],key[1]graph[u]=append(graph[u],Edge{to:v,weight:w})}dist:=make([]int32,n+1)// 1-based indexingfori:=int32(1);i<=n;i++{dist[i]=int32(math.MaxInt32)}dist[s]=0pq:=&MinHeap{}heap.Init(pq)heap.Push(pq,Item{s,0})visited:=make([]bool,n+1)forpq.Len()>0{curr:=heap.Pop(pq).(Item)u:=curr.nodeifvisited[u]{continue}visited[u]=truefor_,e:=rangegraph[u]{v:=e.toifdist[u]+e.weight<dist[v]{dist[v]=dist[u]+e.weightheap.Push(pq,Item{v,dist[v]})}}}// Build result excluding sourceresult:=[]int32{}fori:=int32(1);i<=n;i++{ifi==s{continue}ifdist[i]==int32(math.MaxInt32){result=append(result,-1)}else{result=append(result,dist[i])}}returnresult}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Dijkstra: Shortest Reach 2
You are viewing a single comment's thread. Return to all comments →
Golang solution