Пример #1
0
    // 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));
    }
Пример #2
0
    // 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);
    }