Advertisement
jasonpogi1669

Simple BFS Traversal using Java

Jun 9th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 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 BFS(int u) {
  39.         LinkedList<Integer> q = new LinkedList<Integer>();
  40.         visited[u] = true;
  41.         q.add(u);
  42.         while ((int) q.size() != 0) {
  43.             u = q.poll();
  44.             ListIterator it = a[u].listIterator();
  45.             while (it.hasNext()) {
  46.                 int v = (int) it.next();
  47.                 if (!visited[v]) {
  48.                     visited[v] = true;
  49.                     System.out.print(" -> " + (v + 1));
  50.                     q.add(v);
  51.                 }
  52.             }
  53.         }
  54.     }
  55.    
  56.     public static void main(String[] args) {
  57.         Scanner in = new Scanner(System.in);
  58.         int tt = in.nextInt();
  59.         for (int qq = 1; qq <= tt; qq++) {
  60.             int n = in.nextInt();
  61.             int m = in.nextInt();
  62.             a = new LinkedList[n];
  63.             for (int i = 0; i < n; i++) {
  64.                 a[i] = new LinkedList();
  65.             }
  66.             for (int i = 0; i < m; i++) {
  67.                 int u = in.nextInt();
  68.                 int v = in.nextInt();
  69.                 --u; --v;
  70.                 a[u].add(v);
  71.                 a[v].add(u);
  72.             }
  73.             visited = new boolean[n];
  74.             Arrays.fill(visited, false);
  75.             for (int u = 0; u < n; u++) {
  76.                 if (!visited[u]) {
  77.                     System.out.print(u + 1);
  78.                     BFS(u);
  79.                     System.out.println();
  80.                 }
  81.             }
  82.             System.out.println("");
  83.         }
  84.     }
  85. }
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement