Question

In: Computer Science

Which graph search method will be better for finding a cycle in an undirected graph: a...

Which graph search method will be better for finding a cycle in an undirected graph: a BTS or a DFS? In detail, describe (create) an algorithm for finding a cycle in any undirected graph, explaining why the algorithm assures to find a cycle if there exists one.

Solutions

Expert Solution

DFS is better for finding cycle in an undirected graph, because

  1. DFS is easier to implement
  2. Once DFS finds a cycle, the stack will contain the nodes forming the cycle. The same is not true for BFS, so you need to do extra work if you want to also print the found cycle. This makes DFS a lot more convenient.
  3. using BFS, you have to explicitly maintaining the history of visited nodes using proper data structures.

DFS is a clear choice.

To detect if there is any cycle in the undirected graph or not, we will use the DFS traversal for the given graph. For every visited vertex v, when we have found any adjacent vertex u, such that u is already visited, and u is not the parent of vertex v. Then one cycle is detected.

We will assume that there are no parallel edges for any pair of vertices.

Input and Output:
Adjacency matrix
   
    0 1 0 0 0
    1 0 1 1 0
    0 1 0 0 1
    0 1 0 0 1
    0 0 1 1 0

Output:
The graph has cycle.

Algorithm

dfs(vertex, visited, parent)

Input: The start vertex, the visited set, and the parent node of the vertex.

Output: True a cycle is found.Begin

add vertex in the visited set

for all vertex v which is adjacent with vertex, do

if v = parent, then

return true

if v is not in the visited set, then

return true

if dfs(v, visited, vertex) is true, then

return true

   done

return false

End hasCycle(graph)

Input: The given graph.

Output: True when a cycle has found.Begin

for all vertex v in the graph, do

if v is not in the visited set, then

go for next iteration

if dfs(v, visited, φ) is true, then //parent of v is null

return true

return false

done

End

Given an undirected graph, how to check if there is a cycle in the graph?

Example,

Input: n = 4, e = 4
Output: Yes
Explanation:
0 1, 1 2, 2 3, 0 2
Diagram:

The diagram clearly shows a cycle 0 to 2 to 1 to 0

Input:n = 4, e = 3
0 1, 1 2, 2 3
Output:No
Explanation:
Diagram:

The diagram clearly shows no cycle

Run a DFS from every unvisited node. Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is joining a node to itself (self-loop) or one of its ancestor in the tree produced by DFS.
To find the back edge to any of its ancestor keep a visited array and if there is a back edge to any visited node then there is a loop and return true.

Algorithm:

  1. Create the graph using the given number of edges and vertices.
  2. Create a recursive function that that current index or vertex, visited and recursion stack.
  3. Mark the current node as visited and also mark the index in recursion stack.
  4. Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true return true.
  5. If the adjacent vertices are already marked in the recursion stack then return true.
  6. Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true, return true.
  7. Else if for all vertices the function returns false return false.

// A Java Program to detect cycle in an undirected graph
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list
// representation
class Graph
{
   private int V; // No. of vertices
   private LinkedList<Integer> adj[]; // Adjacency List Represntation

   // Constructor
   Graph(int v) {
       V = v;
       adj = new LinkedList[v];
       for(int i=0; i<v; ++i)
           adj[i] = new LinkedList();
   }

   // Function to add an edge into the graph
   void addEdge(int v,int w) {
       adj[v].add(w);
       adj[w].add(v);
   }

   // A recursive function that uses visited[] and parent to detect
   // cycle in subgraph reachable from vertex v.
   Boolean isCyclicUtil(int v, Boolean visited[], int parent)
   {
       // Mark the current node as visited
       visited[v] = true;
       Integer i;

       // Recur for all the vertices adjacent to this vertex
       Iterator<Integer> it = adj[v].iterator();
       while (it.hasNext())
       {
           i = it.next();

           // If an adjacent is not visited, then recur for that
           // adjacent
           if (!visited[i])
           {
               if (isCyclicUtil(i, visited, v))
                   return true;
           }

           // If an adjacent is visited and not parent of current
           // vertex, then there is a cycle.
           else if (i != parent)
               return true;
       }
       return false;
   }

   // Returns true if the graph contains a cycle, else false.
   Boolean isCyclic()
   {
       // Mark all the vertices as not visited and not part of
       // recursion stack
       Boolean visited[] = new Boolean[V];
       for (int i = 0; i < V; i++)
           visited[i] = false;

       // Call the recursive helper function to detect cycle in
       // different DFS trees
       for (int u = 0; u < V; u++)
           if (!visited[u]) // Don't recur for u if already visited
               if (isCyclicUtil(u, visited, -1))
                   return true;

       return false;
   }


   // Driver method to test above methods
   public static void main(String args[])
   {
       // Create a graph given in the above diagram
       Graph g1 = new Graph(5);
       g1.addEdge(1, 0);
       g1.addEdge(0, 2);
       g1.addEdge(2, 1);
       g1.addEdge(0, 3);
       g1.addEdge(3, 4);
       if (g1.isCyclic())
           System.out.println("Graph contains cycle");
       else
           System.out.println("Graph doesn't contains cycle");

       Graph g2 = new Graph(3);
       g2.addEdge(0, 1);
       g2.addEdge(1, 2);
       if (g2.isCyclic())
           System.out.println("Graph contains cycle");
       else
           System.out.println("Graph doesn't contains cycle");
   }
}

Output:

Graph contains cycle
Graph doesn't contain cycle

Complexity Analysis:

  • Time Complexity: O(V+E).
    The program does a simple DFS Traversal of the graph which is represented using adjacency list. So the time complexity is O(V+E).

Related Solutions

Write a program in java that detects if there is a cycle in an undirected graph...
Write a program in java that detects if there is a cycle in an undirected graph using DFS Two lines of input: 1. Two integers V for the number of vertices and E for the number of edges respectively. 2. List of integers that shows how the graph is connected. Ex input: 4 4 01020323 Output: Graph contains cycle Ex input: 5 4 01020314 Output: Graph doesn't contains cycle
Give an algorithm to detect whether a given undirected graph contains a cycle. If the graph...
Give an algorithm to detect whether a given undirected graph contains a cycle. If the graph contains a cycle, then your algorithm should output one. (It should not output all cycles in the graph, just one of them.) The running time of your algorithm should be O(m + n) for a graph with n nodes and m edges.
give an example of a simple, undirected, weighted graph such that breadth-firstsearch outputs a search-tree that...
give an example of a simple, undirected, weighted graph such that breadth-firstsearch outputs a search-tree that is not a single source shortest path tree. Youranswer must (a) Specify the graphG= (V, E)by specifyingVandE. (b) Specify the weight functionw. (c) Specify an ordering of the vertices and the search-tree output by breadth-first search assuming the specified graph and ordering. (d) Specify a valid single-source shortest path treeT= (V, ET)by specifyingETand its root, the first vertex in your specified ordering. (e) Include...
Using C++: Create a function to search an undirected weighted graph and find the highest weighted...
Using C++: Create a function to search an undirected weighted graph and find the highest weighted edge between two specific values. This should include a class declaration and the definition for all required members that are needed to support the search. NO NEED to code those members. You can assume any other data structures such as stack, heap, or linked list is defined (so you can use their standard functions without declaring or defining them).
You are given an undirected graph G = ( V, E ) in which the edge...
You are given an undirected graph G = ( V, E ) in which the edge weights are highly restricted. In particular, each edge has a positive integer weight from 1 to W, where W is a constant (independent of the number of edges or vertices). Show that it is possible to compute the single-source shortest paths in such a graph in O(E+V) time.
Give an algorithm that constructs an undirected connected graph, which allows for labeling of the n...
Give an algorithm that constructs an undirected connected graph, which allows for labeling of the n vertices u - v <= k for every edge (u,v), where k is some constant. All nodes have a unique label.
ive an example of a simple, undirected graph that has a single source shortestpath tree which...
ive an example of a simple, undirected graph that has a single source shortestpath tree which breadth-first search will not return for any ordering of its vertices.Your answer must (a) Specify the graphG= (V, E)by specifying V and E. (b) Specify the single source shortest path treeT= (V, ET) by specifying E T and also specifying the roots∈V. (c) and include a clear explanation of why the breadth-first search algorithm we discussed in class will never produce T for any...
Construct a connected undirected graph with 25 or more nodes. - Draw your graph in a...
Construct a connected undirected graph with 25 or more nodes. - Draw your graph in a diagram. - Draw the adjacency matrix of your graph. - Draw the adjacency list of your graph. - Run the BFS algorithm on your graph and complete the chart discussed in class. Detailed steps, including the changes of node color, predecessor, etc., as discussed in class, are required.
Design a linear-time algorithm which, given an undirected graph G and a particular edge e in...
Design a linear-time algorithm which, given an undirected graph G and a particular edge e in it, determines whether G has a cycle containing e. Your algorithm should also return the length (number of edges) of the shortest cycle containing e, if one exists. Just give the algorithm, no proofs are necessary. Hint: you can use BFS to solve this.
In a simple undirected graph H the sum of vertex degrees is 60. What is the...
In a simple undirected graph H the sum of vertex degrees is 60. What is the smallest possible number of vertices in this graph? What is the largest possible number of vertices in the graph?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT