예제 #1
0
        public DFSDiagraph(Digraph graph)
        {
            marked = new bool[graph.V];
            order = new Stack<int>(graph.V);

            for (int v = 0; v < graph.V; v++)
                if (!marked[v]) dfs(graph, v);
        }
예제 #2
0
        public Digraph reverse()
        {
            Digraph R = new Digraph(V);
            for (int v = 0; v < V; v++)
                foreach (var w in getAdj(v))
                    R.addEdge(w, v);

            return R;
        }
예제 #3
0
        public DirectedCycle(Digraph g)
        {
            marked = new bool[g.V];
            onStack = new bool[g.V];
            cycle = new Stack<int>(g.V);
            edgeTo = new int[g.V];

            for (int v = 0; v < g.V; v++)
                if (!marked[v])
                    dfs(g, v);
        }
예제 #4
0
        private void dfs(Digraph g, int v)
        {
            marked[v] = true;
            foreach (var w in g.getAdj(v))
            {
                if (!marked[w])
                    dfs(g, w);
            }

            order.Push(v);
        }
예제 #5
0
        private char[] find(String[] orderStrings)
        {
            Digraph g = new Digraph(26);

            int j = 0;
            for (int i = 0; i < orderStrings.Length - 1; i++)
            {
                string high = orderStrings[i + 1];
                string low = orderStrings[i];
                int minLength = Math.Min(low.Length, high.Length);

                for (j = 0; j < minLength; j++)
                {
                    if (low[j] == high[j])
                        continue;

                    if (low[j] != high[j])
                        g.addEdge(get(low[j]), get(high[j]));
                }
            }

            DirectedCycle cycle = new DirectedCycle(g);
            if (cycle.hasCycle()) {
                foreach (var c in cycle.getCycle())
                    Console.Write(c + " -> ");

                Console.WriteLine();
                return null;
            }

            List<char> orders = new List<char>();
            DFSDiagraph dfs = new DFSDiagraph(g);
            foreach (var v in dfs.sort()) {
                orders.Add(get(v));
            }

            return orders.ToArray();
        }
예제 #6
0
        private void dfs(Digraph g, int v)
        {
            marked[v] = true;
            onStack[v] = true;

            foreach (int w in g.getAdj(v))
            {
                if(hasCycle()) return;
                else if (!marked[w])
                {
                    edgeTo[w] = v;
                    dfs(g, w);
                }
                else if (onStack[w])
                {
                    for (int x = v; x != w; x = edgeTo[x])
                        cycle.Push(x);

                    cycle.Push(w);
                    cycle.Push(v);
                }
            }

            onStack[v] = false;
        }