Question

Using java .Write a program to determine whether a given unweighted undirected graph G contains a...

Using java .Write a program to determine whether a given unweighted undirected graph G contains a cycle or not

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The algorithm for verifying whether a graph contains a cycle or not.

import java.io.*;
import java.util.*;

class Graph
{
   public LinkedList<Integer> matrix[];
   public int V;
   void edge(int v,int w){
       matrix[v].add(w);
       matrix[w].add(v);
   }
   Boolean cyclicCondition(int v, Boolean vis[], int parent)
   {
       vis[v]=true;
       Integer i;
       Iterator<Integer> it = matrix[v].iterator();
       while (it.hasNext())
       {
           i = it.next();
           if (!vis[i])
           {
               if (cyclicCondition(i, vis, v)) {
                   return true;
               }
           }
       else if (i != parent) {
               return true;
           }
       }
       return false;
   }
   Graph(int v){
       V = v;
       matrix= new LinkedList[v];
       for(int i=0; i<v; ++i){
           matrix[i] = new LinkedList();
       }
   }
   Boolean isCyclic()
   {
       Boolean visited[] = new Boolean[V];
       for (int i = 0; i < V; i++)
           visited[i] = false;
           for (int u = 0; u < V; u++) {
               if (!visited[u]){
                   if (cyclicCondition(u, visited, -1)){
                       return true;
                   }
               }
           }
       return false;
   }
  
   public static void main(String args[])
   {
       Graph g1 = new Graph(6);
       g1.edge(3,4);
       g1.edge(1,4);
       g1.edge(4,5);
       g1.edge(1,3);
       g1.edge(4,2);
       g1.edge(3,2);
       if (g1.isCyclic()) {
           System.out.println("cycle is present");
       }
       else{
           System.out.println("no cycle");
       }
   }
}

Add a comment
Know the answer?
Add Answer to:
Using java .Write a program to determine whether a given unweighted undirected graph G contains a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT