Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package main;
- /**
- *
- * @author markjasongalang
- */
- /**
- *
- * Use this as input: (copy-paste in terminal)
- * 3
- * 4 2
- * 1 2
- * 2 3
- * 5 3
- * 1 2
- * 2 3
- * 1 3
- * 6 3
- * 1 2
- * 3 4
- * 5 6
- *
- */
- import java.io.*;
- import java.util.*;
- public class Main {
- static LinkedList<Integer> a[];
- static boolean visited[];
- static void BFS(int u) {
- LinkedList<Integer> q = new LinkedList<Integer>();
- visited[u] = true;
- q.add(u);
- while ((int) q.size() != 0) {
- u = q.poll();
- ListIterator it = a[u].listIterator();
- while (it.hasNext()) {
- int v = (int) it.next();
- if (!visited[v]) {
- visited[v] = true;
- System.out.print(" -> " + (v + 1));
- q.add(v);
- }
- }
- }
- }
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int tt = in.nextInt();
- for (int qq = 1; qq <= tt; qq++) {
- int n = in.nextInt();
- int m = in.nextInt();
- a = new LinkedList[n];
- for (int i = 0; i < n; i++) {
- a[i] = new LinkedList();
- }
- for (int i = 0; i < m; i++) {
- int u = in.nextInt();
- int v = in.nextInt();
- --u; --v;
- a[u].add(v);
- a[v].add(u);
- }
- visited = new boolean[n];
- Arrays.fill(visited, false);
- for (int u = 0; u < n; u++) {
- if (!visited[u]) {
- System.out.print(u + 1);
- BFS(u);
- System.out.println();
- }
- }
- System.out.println("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement