fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. Scanner sc = new Scanner(System.in);
  12.  
  13. int n = sc.nextInt();
  14. int edges = sc.nextInt();
  15.  
  16. List<Integer>[] adjList = new List[n + 1];
  17. for (int i = 0; i <= n; i++) {
  18. adjList[i] = new ArrayList<>();
  19. }
  20.  
  21. for (int i = 0; i < edges; i++) {
  22. int u = sc.nextInt();
  23. int v = sc.nextInt();
  24. adjList[u].add(v);
  25. adjList[v].add(u);
  26. }
  27.  
  28. sc.close();
  29.  
  30. runDFS(n, adjList);
  31. }
  32. public static void runDFS(int vertices, List<Integer>[] adjList) {
  33. boolean[] visited = new boolean[vertices + 1];
  34.  
  35. for (int i = 1; i <= vertices; i++) {
  36. if (!visited[i]) {
  37. dfs(i, adjList, visited);
  38. }
  39. }
  40. System.out.println("end");
  41. }
  42.  
  43. private static void dfs(int currentNode, List<Integer>[] adjList, boolean[] visited) {
  44. visited[currentNode] = true;
  45. System.out.print(currentNode + " -> ");
  46.  
  47. for (int neighbor : adjList[currentNode]) {
  48. if (!visited[neighbor]) {
  49. dfs(neighbor, adjList, visited);
  50. }
  51. }
  52. }
  53. }
Success #stdin #stdout 0.21s 58964KB
stdin
8 7 
1 2
1 3
2 4 
2 5 
3 6 
3 7 
5 8
stdout
1 -> 2 -> 4 -> 5 -> 8 -> 3 -> 6 -> 7 -> end