import
java.util.*;
class
Graph
{
private
Map<Integer, List<Integer>> adjacencyList;
public
Graph(
int
v)
{
adjacencyList =
new
HashMap<Integer, List<Integer>>();
for
(
int
i =
1
; i <= v; i++)
{
adjacencyList.put(i,
new
LinkedList<Integer>());
}
}
public
void
setEdge(
int
src,
int
dest)
{
List<Integer> neighbours = adjacencyList.get(src);
neighbours.add(dest);
}
public
Graph checkAcyclic()
{
Integer count =
0
;
Iterator<Integer> nodes =
this
.adjacencyList.keySet().iterator();
Integer size =
this
.adjacencyList.size() -
1
;
while
(nodes.hasNext())
{
Integer i = nodes.next();
List<Integer> adjList =
this
.adjacencyList.get(i);
if
(count == size)
{
return
this
;
}
if
(adjList.size() ==
0
)
{
count++;
Iterator<Integer> neighbour
=
this
.adjacencyList.keySet().iterator();
while
(neighbour.hasNext())
{
Integer j = neighbour.next();
List<Integer> edges =
this
.adjacencyList.get(j);
if
(edges.contains(i))
{
edges.remove(i);
}
}
this
.adjacencyList.remove(i);
nodes =
this
.adjacencyList.keySet().iterator();
}
}
return
this
;
}
public
boolean
getFeedbackEdgeSet()
{
int
v=
this
.adjacencyList.size();
boolean
flag =
false
;
int
[] visited =
new
int
[v +
1
];
Iterator<Integer> nodes
=
this
.adjacencyList.keySet().iterator();
while
(nodes.hasNext())
{
Integer i = nodes.next();
List<Integer> neighbours =
this
.adjacencyList.get(i);
visited[i] =
1
;
if
(neighbours.size() !=
0
)
{
for
(
int
j =
0
; j < neighbours.size(); j++)
{
if
(visited[neighbours.get(j)] ==
1
)
{
flag =
true
;
System.out.print(
"( "
+i+
" -> "
+
neighbours.get(j)+
" ) "
);
}
else
{
visited[neighbours.get(j)] =
1
;
}
}
}
}
return
flag;
}
}
public
class
GFG
{
public
static
void
main(String args[])
{
int
v =
4
;
int
e =
5
;
Graph g =
new
Graph(v);
g.setEdge(
1
,
2
);
g.setEdge(
2
,
3
);
g.setEdge(
4
,
3
);
g.setEdge(
1
,
4
);
g.setEdge(
3
,
1
);
g = g.checkAcyclic();
System.out.print(
"Feedback Edge Set: "
);
if
(g.getFeedbackEdgeSet() ==
false
)
{
System.out.println(
"None"
);
}
}
}