Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4.  
  5. public class A {
  6.     static int N;
  7.     static int M;
  8.     static int v;
  9.     static int graph[][];
  10.     static ArrayList depth[];
  11.     static int used[];
  12.  
  13.     public static void BFS(int k, int v) {
  14.         used[v - 1] = 1;
  15.         for (int j = 0; j < depth[k].size(); j++) {
  16.             for (int i = 0; i < N; i++) {
  17.                 if (graph[(int) depth[k].get(j) - 1][i] == 1) {
  18.                     if (used[i] != 1) {
  19.                         used[i] = 1;
  20.                         depth[k + 1].add(i + 1);
  21.                     }
  22.                 }
  23.             }
  24.         }
  25.         if (k != N - 1) {
  26.             for (int i = 0; i < depth[k+1].size(); i++) {
  27.                 BFS(k + 1, depth[k].get(i));
  28.             }
  29.         }
  30.     }
  31.  
  32.     public static void main(String[] args) {
  33.         Scanner sc = new Scanner(System.in);
  34.         N = sc.nextInt();
  35.         M = sc.nextInt();
  36.         v = sc.nextInt();
  37.         //p = new int[N];
  38.         graph = new int[N][N];
  39.         for (int i = 0; i < M; i++) {
  40.             int a = sc.nextInt();
  41.             int b = sc.nextInt();
  42.             graph[a - 1][b - 1] = 1;
  43.             graph[b - 1][a - 1] = 1;
  44.         }
  45.         depth = new ArrayList<int>()[N];
  46.         depth[0] = new ArrayList();
  47.         used = new int[N];
  48.         depth[0].add(v);
  49.         BFS(0, v);
  50.         int places = 0;
  51.         for (int i = 0; i < N; i++) {
  52.             if (used[i] == 1) {
  53.                 places = places + 1;
  54.             }
  55.         }
  56.         System.out.println(places);
  57.         for (int i = 0; i < N; i++) {
  58.             for (int j = 0; j < depth[i].size(); j++) {
  59.                 System.out.print(depth[i].get(j) + " ");
  60.             }
  61.         }
  62.  
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement