// Complete the roadsAndLibraries function below. static long roadsAndLibraries(int n, int c_lib, int c_road, int[][] cities) { if (c_road > c_lib) { return(n * c_lib); } var gragh = new Gragh(n, false); for (int i = 0; i < cities.Length; i++) { gragh.AddEdge(cities[i][0], cities[i][1]); } return(DFS(gragh, c_lib, c_road)); }
private static long DFS(Gragh gragh, int c_lib, int c_road) { var visited = new bool[gragh.CitiesCount + 1]; long cost = 0; for (int i = 1; i <= gragh.CitiesCount; i++) { if (!visited[i]) { var routesCount = DFSUtil(gragh, visited, i); cost += (routesCount - 1) * c_road + c_lib; } } return(cost); }
// Complete the findShortest function below. /* * For the unweighted graph, <name>: * * 1. The number of nodes is <name>Nodes. * 2. The number of edges is <name>Edges. * 3. An edge exists between <name>From[i] to <name>To[i]. * */ static int findShortest(int graphNodes, int[] graphFrom, int[] graphTo, long[] colors, int val) { // solve here var gragh = new Gragh(graphNodes, false); for (int i = 0; i < graphFrom.Length; i++) { gragh.AddEdge(new Vertix(graphFrom[i], colors[graphFrom[i] - 1]), new Vertix(graphTo[i], colors[graphTo[i] - 1])); } var visited = new HashSet <Vertix>(new EqualityComparer()); var q = new Queue <Tuple <int, Vertix> >(); foreach (var vertixKV in gragh.VertixesWithEdges) { var parentVertix = vertixKV.Key; //if (!visited.Contains(parentVertix)) { visited.Add(parentVertix); if (parentVertix.Color == val) { var path = 0; q.Enqueue(new Tuple <int, Vertix>(0, parentVertix)); while (q.Count > 0) { var qItem = q.Dequeue(); // BFS foreach (var child in gragh.VertixesWithEdges[qItem.Item2]) { if (!visited.Contains(child)) { q.Enqueue(new Tuple <int, Vertix>(qItem.Item1 + 1, child)); if (child.Color == val) { return(qItem.Item1 + 1); } } } } } } } return(-1); }
private static int DFSUtil(Gragh gragh, bool[] visited, int vertix) { int routesCount = 1; visited[vertix] = true; if (gragh.VertixesWithEdges.ContainsKey(vertix)) { foreach (var edge in gragh.VertixesWithEdges[vertix]) { if (!visited[edge]) { routesCount += DFSUtil(gragh, visited, edge); } } } return(routesCount); }