Skip to content

Commit 18b3925

Browse files
Create DFSUsingRecursion.java
1 parent 53d6dec commit 18b3925

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Graphs/DFSUsingRecursion.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.util.*;
2+
3+
class DFSUsingRecursion{
4+
static class Edge{
5+
int src,dest;
6+
7+
Edge(int src, int dest){
8+
this.src = src;
9+
this.dest = dest;
10+
}
11+
}
12+
13+
static void makeGraph(ArrayList<ArrayList<Integer>> graph, int v){
14+
for(int i = 0; i<v; i++){
15+
graph.add(new ArrayList<Integer>());
16+
}
17+
}
18+
19+
static void fillGraph(ArrayList<ArrayList<Integer>> graph, int v, ArrayList<Edge> edgeList){
20+
for(int i=0; i<edgeList.size(); i++){
21+
int s = edgeList.get(i).src;
22+
int d = edgeList.get(i).dest;
23+
graph.get(s).add(d);
24+
}
25+
}
26+
27+
static void dfs(ArrayList<ArrayList<Integer>> graph, int v, boolean[] visited, int src){
28+
if(visited[src]){
29+
return;
30+
}
31+
32+
visited[src] = true;
33+
System.out.println(src);
34+
35+
for(int neighbour: graph.get(src)){
36+
if(!visited[neighbour]){
37+
dfs(graph, visited, neighbour);
38+
}
39+
}
40+
}
41+
42+
public static void main(String[] args){
43+
Scanner input = new Scanner(System.in);
44+
45+
System.out.println("Enter the number of vertices: ");
46+
int v = input.nextInt();
47+
System.out.println("Enter the number of edges: ");
48+
int e = input.nextInt();
49+
50+
ArrayList<Edge> edgeList = new ArrayList<Edge>();
51+
52+
for(int i = 0; i<e; i++){
53+
edgeList.add(new Edge(input.nextInt(), input.nextInt()));
54+
}
55+
56+
ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
57+
makeGraph(graph, v);
58+
fillGraph(graph, v, edgeList);
59+
60+
boolean[] visited = new boolean[v];
61+
dfs(graph, v, visited, 0);
62+
63+
input.close();
64+
}
65+
}

0 commit comments

Comments
 (0)