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