Input:
Graph(directed and undirected)
Objective:
Finding Mother Vertex.
Approach:
Simple approach using DFS, more time complexity. This helps just to understand DFS better.
Implemented using java.
package dfs;
import java.io.*;
import java.util.*;
public class Graph {
int V;
LinkedList<Integer> adj[];
Graph(int V)
{
this.V = V;
adj = new LinkedList[V];
for(int i=0;i<V;i++)
adj[i] = new LinkedList();
}
void addEdge(int u,int v)
{
adj[u].add(v);
}
void DFS_Util(boolean visited[], int s)
{
visited[s] = true;
// System.out.println(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext())
{
int n = i.next();
if(!visited[n])
DFS_Util(visited,n);
}
}
int DFS(int s)
{
int ans = 0;
boolean visited[] = new boolean[V];
DFS_Util(visited,s);
for(int i=0;i<V;i++)
{
if(visited[i] == false)
ans=0;
else
ans=1;
}
return ans;
}
public static void main(String args[])
{
Graph g = new Graph(7);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(4, 1);
g.addEdge(6, 4);
g.addEdge(5, 6);
g.addEdge(5, 2);
g.addEdge(6, 0);
for(int i=0;i<7;i++)
{
if(g.DFS(i) != 1)
continue;
else
{
System.out.println(i);
break;
}
}
}
}
No comments:
Post a Comment