Advertisement
jasonpogi1669

Simple DFS Traversal using Java

Jun 9th, 2021
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package main;
  7.  
  8. /**
  9.  *
  10.  * @author markjasongalang
  11.  */
  12.  
  13. /**
  14.  *
  15.  *  Use this as input: (copy-paste in terminal)
  16.  *  3
  17.  *  4 2
  18.  *  1 2
  19.  *  2 3
  20.  *  5 3
  21.  *  1 2
  22.  *  2 3
  23.  *  1 3
  24.  *  6 3
  25.  *  1 2
  26.  *  3 4
  27.  *  5 6
  28.  *
  29.  */
  30.  
  31. import java.io.*;
  32. import java.util.*;
  33.  
  34. public class Main {
  35.     static LinkedList<Integer> a[];
  36.     static boolean visited[];
  37.    
  38.     static void DFS(int u) {
  39.         visited[u] = true;
  40.         ListIterator it = a[u].listIterator(0);
  41.         while (it.hasNext()) {
  42.             int v = (int) it.next();
  43.             if (!visited[v]) {
  44.                 System.out.print(" -> " + (v + 1));
  45.                 DFS(v);
  46.             }
  47.         }
  48.     }
  49.    
  50.     public static void main(String[] args) {
  51.         Scanner in = new Scanner(System.in);
  52.         int tt = in.nextInt();
  53.         for (int qq = 1; qq <= tt; qq++) {
  54.             int n = in.nextInt();
  55.             int m = in.nextInt();
  56.             a = new LinkedList[n];
  57.             for (int i = 0; i < n; i++) {
  58.                 a[i] = new LinkedList();
  59.             }
  60.             for (int i = 0; i < m; i++) {
  61.                 int u = in.nextInt();
  62.                 int v = in.nextInt();
  63.                 --u; --v;
  64.                 a[u].add(v);
  65.                 a[v].add(u);
  66.             }
  67.             visited = new boolean[n];
  68.             Arrays.fill(visited, false);
  69.             for (int u = 0; u < n; u++) {
  70.                 if (!visited[u]) {
  71.                     System.out.print(u + 1);
  72.                     DFS(u);
  73.                     System.out.println();
  74.                 }
  75.             }
  76.             System.out.println("");
  77.         }
  78.     }
  79. }
  80.  
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement