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