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.
Hello, I've watched the Gayle Laakmann McDowell video and I just tried to keep as close as possible to her example. This is my solution in C#. It runs in time for each test case on the site.
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;classSolution{publicclassGraph{privatereadonlyDictionary<int,Node>_nodeLookup=newDictionary<int,Node>();publicintSize{get;set;}publicclassNode{privateint_id;publicintDistanceToSource{get;set;}publicNode(intid){_id=id;DistanceToSource=-1;}publicList<Node>Adjacent=newList<Node>();}publicGraph(intsize){Size=size;for(vari=1;i<=size;i++)AddNode(i);}publicNodeGetNode(intid){return_nodeLookup[id];}privatevoidAddNode(intnodeId){varn=newNode(nodeId);_nodeLookup.Add(nodeId,n);}publicvoidAddEdge(intfirst,intsecond){varsource=GetNode(first);vardestination=GetNode(second);// Bidirectional Graph needs both edgessource.Adjacent.Add(destination);destination.Adjacent.Add(source);}publicint[]ShortestReach(intstartId){varnextToVisit=newQueue<Node>();varstartNode=GetNode(startId);startNode.DistanceToSource=0;nextToVisit.Enqueue(startNode);while(nextToVisit.Any()){varnode=nextToVisit.Dequeue();foreach(varadjinnode.Adjacent){if(adj.DistanceToSource>-1&&adj.DistanceToSource<=node.DistanceToSource+1)continue;adj.DistanceToSource=node.DistanceToSource+1;nextToVisit.Enqueue(adj);}}varshortestReach=_nodeLookup.Where(i=>i.Key!=startId).OrderBy(i=>i.Key).Select(i=>i.Value.DistanceToSource).ToArray();returnshortestReach;}}publicstaticvoidMain(string[]args){varq=Convert.ToInt32(Console.ReadLine());for(vari=0;i<q;i++){vartemp=Console.ReadLine().Split(' ').Select(int.Parse).ToArray();varn=temp[0];varm=temp[1];vargraph=newGraph(n);for(varj=0;j<m;j++){temp=Console.ReadLine().Split(' ').Select(int.Parse).ToArray();graph.AddEdge(temp[0],temp[1]);}varstartId=Convert.ToInt32(Console.ReadLine());varshortestReach=graph.ShortestReach(startId);foreach(vardistinshortestReach){Console.Write(dist!=-1?dist*6:dist);Console.Write(' ');}Console.WriteLine();}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach in a Graph
You are viewing a single comment's thread. Return to all comments →
Hello, I've watched the Gayle Laakmann McDowell video and I just tried to keep as close as possible to her example. This is my solution in C#. It runs in time for each test case on the site.