GeeksforGeeks App
Open App Browser
Continue

# Java Program to Find a Good Feedback Vertex Set in a Graph

A feedback vertex set of a graph is a set of vertices whose removal leaves a graph without cycles. The following graph becomes a Directed acyclic Graph.

Examples:

```Input:
Enter the number of vertices:
4
Enter the number of edges:
5
Enter the graph: <Start> <end>
1 2
2 3
3 4
4 1
1 3
Output:
The Graph is:
1-> 2-> 3
2-> 3
3-> 4
4-> 1
The set of edges in FeedBack arc set: 2 - 3
4 - 1

Input:
Enter the number of vertices:
5
Enter the number of edges:
5
Enter the graph: <Start> <end>
1 2
2 4
5 3
5 1
4 3.
Output:
The Graph is:
1-> 2
2-> 4
4-> 3
5-> 3-> 1
The set of edges in FeedBack arc set: None```

Approach:

• We will declare all the needed variables, like count, edges, start, end and vertices
• Now we will call the Graph Function: we will take and store the values in an adjacent list which will be declared as a variable of the class.
• Then keeping the while condition in, we will take the input of all the starting and ending points of a constructor in a graph.
• Now calling the set edge function: we check if the adjacent list is empty, if not we will store the values of it, in it.
• Then we call the printGraph() function– This method will basically print the graph, wherein we iterate the loop and print the elements, and we store it in a list
• Then we call the object of the class and call the check function — Each iterator checks if we have taken the value only a single time If the value is repeated we remove it
• Then we set the Feedback vertex and call the function -We would now check if we have visited all the nodes, if we did we would count it, and if we didn’t we would keep it equal to 1. Now using all this we would find which node can be removed.

Code:

## Java

 `// Java Program to Find a Good Feedback Vertex Set in a``// Graph` `import` `java.util.HashMap;``import` `java.util.Iterator;``import` `java.util.LinkedList;``import` `java.util.List;``import` `java.util.Map;``import` `java.util.Scanner;` `// Let us declare a class``class` `Edge` `{` `    ``// We have declared a Map with Integer as its parameters``    ``// Named adjacentList` `    ``private` `Map > adjacentList;` `    ``// Now lets us declare a function called "Graph"``    ``public` `Edge(``int` `vertices)``    ``{``        ``// Now taking the new List as a HashMap``        ``adjacentList``            ``= ``new` `HashMap >();` `        ``// Iterating i from 1 till vertices``        ``for` `(``int` `i = ``1``; i <= vertices; i++) {``            ``// Adding them to a new LinkedList``            ``adjacentList.put(i, ``new` `LinkedList());``        ``}``    ``}` `    ``// We are now declaring  a class edge``    ``// It has two parameters start and end``    ``public` `void` `set_Edge(``int` `end, ``int` `start)``    ``{``        ``// We will write the condition for checking``        ``// If the vertices are empty``        ``if` `(end > adjacentList.size()``            ``|| start > adjacentList.size())` `            ``System.out.println(``"There are no vertices"``);` `        ``// Now if the input isn't zero``        ``// We will add them to a new list``        ``List fls = adjacentList.get(start);` `        ``fls.add(end);``    ``}` `    ``// We created a list function called get edge``    ``// Help us to return the edges of a Graph``    ``public` `List get_Edge(``int` `end)``    ``{` `        ``// Returning the edges back``        ``return` `adjacentList.get(end);``    ``}` `    ``// Now let us check``    ``public` `Edge check()``    ``{` `        ``// Now let us keep the count as 0``        ``Integer count = ``0``;` `        ``// Let us iterator for easy function``        ``Iterator iterator``            ``= ``this``.adjacentList.keySet().iterator();` `        ``// Let us take a size variable of adjacent List``        ``Integer size = ``this``.adjacentList.size() - ``1``;` `        ``// Iterating it till the end of the loop``        ``while` `(iterator.hasNext()) {` `            ``// Now taking the variable which is an iterator``            ``Integer i = iterator.next();` `            ``// Declaring a new list adjlist``            ``List adjList``                ``= ``this``.adjacentList.get(i);` `            ``// checking for equal size we would return the``            ``// same``            ``if` `(count == size) {``                ``return` `this``;``            ``}` `            ``// Now keeping the condition adjList==0``            ``if` `(adjList.size() == ``0``) {` `                ``// Every time we run the if``                ``// we increase the count``                ``count++;` `                ``// Now taking an iterator Right``                ``Iterator iteratorR``                    ``= ``this``.adjacentList.keySet().iterator();` `                ``// Again iterating completely over the new``                ``// Iterator``                ``while` `(iteratorR.hasNext()) {` `                    ``// Having the new R , help us to iterate``                    ``// the new Iterator``                    ``Integer R = iteratorR.next();` `                    ``// New List is taken` `                    ``List lit``                        ``= ``this``.adjacentList.get(R);` `                    ``// This if condition will help not to``                    ``// have` `                    ``// Any duplicate values inside the new``                    ``// List``                    ``if` `(lit.contains(i)) {``                        ``// If we have one we would remove it` `                        ``lit.remove(i);``                    ``}``                ``}` `                ``// The below line would help us to remove``                ``// the values` `                ``// Of the adjacent List as we move on to``                ``// make the vertices` `                ``// The other values are simultaneously``                ``// removed.``                ``this``.adjacentList.remove(i);` `                ``iterator``                    ``= ``this``.adjacentList.keySet().iterator();``            ``}``        ``}` `        ``return` `this``;``    ``}` `    ``// This function helps us to print a graph``    ``public` `void` `printGraph()` `    ``{` `        ``System.out.println(``"The Graph is:"``);` `        ``// Now let us taken an iterator and try to print it` `        ``// This iterator contains the values of the new``        ``// graph``        ``Iterator iterator``            ``= ``this``.adjacentList.keySet().iterator();` `        ``// Now  iterating the values``        ``while` `(iterator.hasNext())` `        ``{` `            ``// taking the variable i to be the next Iterator``            ``Integer i = iterator.next();` `            ``// Taking a list which will help us have the``            ``// side edges.``            ``List edgeList = ``this``.get_Edge(i);` `            ``// Now checking the edge list if it is not zero``            ``if` `(edgeList.size() != ``0``)` `            ``{` `                ``// print them out``                ``System.out.print(i);` `                ``// now iterating it till edgelist``                ``for` `(``int` `j = ``0``; j < edgeList.size(); j++)` `                ``{` `                    ``// Now printing the graph in its pattern``                    ``System.out.print(``"-> "``                                     ``+ edgeList.get(j));``                ``}` `                ``System.out.println();``            ``}``        ``}``    ``}` `    ``// Closing the function` `    ``// Now finding the FeedbackArc set``    ``public` `boolean` `getFeedbackArcSet(``int` `vertices)` `    ``{` `        ``// Taking boolean flag false``        ``boolean` `flag = ``false``;` `        ``// Now taking visited array``        ``// This array length is vertices+1``        ``int``[] visited = ``new` `int``[vertices + ``1``];` `        ``// This iterator has values of adjacent list``        ``Iterator iterator``            ``= ``this``.adjacentList.keySet().iterator();` `        ``// Now let us see the feedback arc``        ``System.out.print(``            ``"The set of edges in FeedBack arc set: "``);` `        ``// Now it has iterator which is next``        ``while` `(iterator.hasNext())` `        ``{` `            ``// Now taking i which will be iterating next``            ``Integer i = iterator.next();` `            ``// Now taking a list of values adjacent list``            ``List list = ``this``.adjacentList.get(i);` `            ``// Visited array to be after i``            ``visited[i] = ``1``;` `            ``// Now taking if the list size not equal to 0``            ``if` `(list.size() != ``0``)` `            ``{` `                ``// We iterate till list size``                ``for` `(``int` `j = ``0``; j < list.size(); j++)` `                ``{` `                    ``// If we have visited the list``                    ``// e will flag it to be true``                    ``if` `(visited[list.get(j)] == ``1``)` `                    ``{` `                        ``flag = ``true``;` `                        ``// Now taking the output of feedback``                        ``// arc``                        ``System.out.println(i + ``" - "``                                           ``+ list.get(j));``                    ``}` `                    ``else` `                    ``{` `                        ``// Now if we don't visit``                        ``// We will be iterating it to 1``                        ``visited[list.get(j)] = ``1``;``                    ``}``                ``}``            ``}``        ``}` `        ``// Return the flag``        ``return` `flag;``    ``}``}` `// Now let us declare the class GFG` `class` `GFG {` `    ``public` `static` `void` `main(String[] args)``    ``{` `        ``// Now let us declare and initialize all the``        ``// variables``        ``int` `vertices = ``4``, e = ``5``, count = ``1``;``        ``int``[] start = { ``1``, ``2``, ``3``, ``4``, ``1` `};``        ``int``[] end = { ``2``, ``3``, ``4``, ``1``, ``3` `};` `        ``// Now let us see  the object of the class``        ``Edge ist;` `        ``// Now let us try the exception.``        ``try` `        ``{` `            ``// printing both the values``            ``System.out.println(``"Number of vertices: "``                               ``+ vertices);` `            ``System.out.println(``"Number of edges: "` `+ e);` `            ``// Now calling the function``            ``ist = ``new` `Edge(vertices);` `            ``// calling the function by iterating the loop``            ``for` `(``int` `i = ``0``; i < e; i++)` `            ``{` `                ``// Now calling the function set_edge``                ``ist.set_Edge(end[i], start[i]);``            ``}` `            ``// Now we are calling the print Graph Function``            ``ist.printGraph();` `            ``// Now we will call the object of class``            ``// and then we called the function check``            ``Edge modified = ist.check();` `            ``// If we dont get the flag to be true``            ``// We can print the output to be None or empty``            ``if` `(modified.getFeedbackArcSet(vertices)``                ``== ``false``)` `            ``{` `                ``System.out.println(``"None"``);``            ``}``        ``}` `        ``// Try for catch``        ``// We print empty nodes``        ``catch` `(Exception E)` `        ``{` `            ``System.out.println(``"Empty Nodes"``);``        ``}``    ``}``}`

Output

```Number of vertices: 4
Number of edges: 5
The Graph is:
1-> 2-> 3
2-> 3
3-> 4
4-> 1
The set of edges in FeedBack arc set: 2 - 3
4 - 1```

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.5700196,"math_prob":0.9231888,"size":8026,"snap":"2023-14-2023-23","text_gpt3_token_len":2185,"char_repetition_ratio":0.15245575,"word_repetition_ratio":0.100733824,"special_character_ratio":0.30438575,"punctuation_ratio":0.14186193,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9987412,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-06-08T19:57:30Z\",\"WARC-Record-ID\":\"<urn:uuid:b17bfcc4-7b97-4906-905f-a55c95e9f766>\",\"Content-Length\":\"275568\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e7709446-850b-49b9-a648-80af99b99258>\",\"WARC-Concurrent-To\":\"<urn:uuid:ad9d16ad-836a-44dd-b383-ff8b9753fdb0>\",\"WARC-IP-Address\":\"23.218.218.77\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/java-program-to-find-a-good-feedback-vertex-set-in-a-graph/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:5CORKK5EU6NUY7DOYYSLO7W7POWABEQH\",\"WARC-Block-Digest\":\"sha1:RWQS5X253H46ITNO3R5FBEKDJ7OTTW7L\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224655092.36_warc_CC-MAIN-20230608172023-20230608202023-00119.warc.gz\"}"}