Interview Question Categories

Triangle Free Graph

Triangle Free Graph


//Check if the graph is triangle free i.e. if the graph doesn't
//have cycles of length 3 then it is said to be triangle free.
namespace TriangleFreeGraph
{
    class Graph
    {
        List<int>[] EdgeList;

        public Graph(int NoOfVertices)
        {
            EdgeList = new List<int>[NoOfVertices];
            for (int i = 0; i < EdgeList.Length; i++)
            {
                EdgeList[i] = new List<int>();
            }
        }

        //Method to add an edge
        public void AddEdge(int S, int D)
        {
            if(!EdgeList[S].Contains(D))
                EdgeList[S].Add(D);
            if(!EdgeList[D].Contains(S))
                EdgeList[D].Add(S);
        }

        private Boolean IsTriangleExists(Boolean[] Visited, int Vertex, int length, int PrevVertex)
        {
            //If there is a cycle of length 3, then return true.
            if (Visited[Vertex] && length == 3) return true;

            //If there is a cycle of length more than 3, continue searching with a different vertex.
            if (Visited[Vertex] || length>3) return false;

            //Mark the vertex as visited.
            Visited[Vertex] = true;

            //Search for triangle recurrsively.
            for (int i = 0; i < EdgeList[Vertex].Count; i++)    //Search for triangle recurrsively.
            {
                if (EdgeList[Vertex][i] == PrevVertex) continue;
                if (IsTriangleExists(Visited, EdgeList[Vertex][i], length + 1, Vertex)) return true;
            }
            //Clear the vertex visited status, for searching a triangle from a different vertex.
            Visited[Vertex] = false;                            
            return false;
        }

        public Boolean IsTriangleExists()
        {
            Boolean[] Visited = new Boolean[EdgeList.Length];
           
            if (IsTriangleExists(Visited, 0, 0, 0)) return true;
            
            return false;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Graph G = new Graph(6);
            G.AddEdge(0, 5);
            G.AddEdge(0, 3);
            G.AddEdge(1, 2);
            G.AddEdge(1, 5);
            G.AddEdge(2, 4);
            G.AddEdge(3, 5);
            G.AddEdge(3, 4);
        
            Console.WriteLine(G.IsTriangleExists());
        }
    }
}

No comments:

Post a Comment