File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Java program to Find a Mother Vertex in a Graph
2
+ import java.io.*;
3
+ import java.util.*;
4
+
5
+ class Graph
6
+ {
7
+ private int V; // No. of vertices
8
+
9
+ // Array of lists for Adjacency List Representation
10
+ private LinkedList<Integer> adj[];
11
+
12
+ // Constructor
13
+ Graph(int v)
14
+ {
15
+ V = v;
16
+ adj = new LinkedList[v];
17
+ for (int i=0; i<v; ++i)
18
+ adj[i] = new LinkedList();
19
+ }
20
+
21
+ //Function to add an edge into the graph
22
+ void addEdge(int v, int w)
23
+ {
24
+ adj[v].add(w); // Add w to v's list.
25
+ }
26
+
27
+ void DFSUtil(int v,boolean visited[])
28
+ {
29
+ visited[v] = true;
30
+
31
+ Iterator<Integer> i = adj[v].listIterator();
32
+ while (i.hasNext())
33
+ {
34
+ int n = i.next();
35
+ if (!visited[n])
36
+ DFSUtil(n, visited);
37
+ }
38
+ }
39
+
40
+ int findMother()
41
+ {
42
+ boolean visited[] = new boolean[V];
43
+ for(int i = 0;i<V;i++){
44
+ visited[i]=false;
45
+ }
46
+
47
+ int a = 0;
48
+ for (int k = 0; k < V; k++)
49
+ {
50
+ if (visited[k] == false)
51
+ {
52
+ DFSUtil(k, visited);
53
+ a = k;
54
+ }
55
+ }
56
+
57
+ for(int j=0;j<V;j++){
58
+ visited[j]=false;
59
+ }
60
+ DFSUtil(a,visited);
61
+ for (int i=0; i<V; i++)
62
+ if (visited[i] == false)
63
+ return -1;
64
+
65
+ return a;
66
+
67
+ }
68
+
69
+ public static void main(String args[])
70
+ {
71
+ Graph g = new Graph(7);
72
+
73
+ g.addEdge(0, 1);
74
+ g.addEdge(0, 2);
75
+ g.addEdge(1, 3);
76
+ g.addEdge(4, 1);
77
+ g.addEdge(6, 4);
78
+ g.addEdge(5, 6);
79
+ g.addEdge(5, 2);
80
+ g.addEdge(6, 0);
81
+
82
+ System.out.println("A mother vertex is:"+g.findMother());
83
+ }
84
+ }
You can’t perform that action at this time.
0 commit comments