Beispiel #1
0
        public void IsUnDirectedCyclic()
        {
            UnDirectedGraph g = new UnDirectedGraph(5);

            g.AddEdge(1, 0);
            g.AddEdge(0, 2);
            g.AddEdge(2, 0);
            g.AddEdge(0, 3);
            g.AddEdge(3, 4);
            Console.WriteLine(IsUnDirectedCyclic(g));
        }
Beispiel #2
0
        private bool IsUnDirectedCyclic(UnDirectedGraph graph)
        {
            for (int idx = 0; idx < graph.Vertices; idx++)
            {
                if (!graph.Visited[idx])
                {
                    if (IsUnDirectedCyclicUtil(graph, idx, -1))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #3
0
        private bool IsUnDirectedCyclicUtil(UnDirectedGraph graph, int vertex, int parent)
        {
            graph.Visited[vertex] = true;

            if (graph.AdjList.ContainsKey(vertex))
            {
                foreach (int idx in graph.AdjList[vertex])
                {
                    if (!graph.Visited[idx])
                    {
                        if (IsUnDirectedCyclicUtil(graph, idx, vertex))
                        {
                            return(true);
                        }
                    }
                    else if (idx != parent)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }