forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS_Recursive.java
More file actions
53 lines (42 loc) · 1.2 KB
/
DFS_Recursive.java
File metadata and controls
53 lines (42 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.ArrayList;
import java.util.Scanner;
public class DFS_Recursive {
/**
* @author Youssef Ali(https://github.com/youssefAli11997/)
*/
private static boolean[] visited;
private static ArrayList<Integer> AdjList[];
public static void DFS_recursive(int parent){
visited[parent] = true;
System.out.print(parent+" ");
for(int child : AdjList[parent]){
if(visited[child])
continue;
DFS_recursive(child);
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many nodes?");
int nodes = in.nextInt();
visited = new boolean[nodes];
AdjList = new ArrayList[nodes];
for(int i=0; i<nodes; i++)
AdjList[i] = new ArrayList<Integer>();
System.out.println("How many edges?");
int edges = in.nextInt();
for(int i=0; i<edges; i++){
System.out.println("To indicate that u is connected to v, type: u v");
int u = in.nextInt();
int v = in.nextInt();
// Assuming that it's an undirected graph
AdjList[u].add(v);
AdjList[v].add(u);
}
System.out.println("Source node?");
int source = in.nextInt();
DFS_recursive(source);
System.out.println();
}
}