Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Scanner;
- public class A {
- static int N;
- static int M;
- static int v;
- static int graph[][];
- static ArrayList depth[];
- static int used[];
- public static void BFS(int k, int v) {
- used[v - 1] = 1;
- for (int j = 0; j < depth[k].size(); j++) {
- for (int i = 0; i < N; i++) {
- if (graph[(int) depth[k].get(j) - 1][i] == 1) {
- if (used[i] != 1) {
- used[i] = 1;
- depth[k + 1].add(i + 1);
- }
- }
- }
- }
- if (k != N - 1) {
- for (int i = 0; i < depth[k+1].size(); i++) {
- BFS(k + 1, depth[k].get(i));
- }
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- N = sc.nextInt();
- M = sc.nextInt();
- v = sc.nextInt();
- //p = new int[N];
- graph = new int[N][N];
- for (int i = 0; i < M; i++) {
- int a = sc.nextInt();
- int b = sc.nextInt();
- graph[a - 1][b - 1] = 1;
- graph[b - 1][a - 1] = 1;
- }
- depth = new ArrayList<int>()[N];
- depth[0] = new ArrayList();
- used = new int[N];
- depth[0].add(v);
- BFS(0, v);
- int places = 0;
- for (int i = 0; i < N; i++) {
- if (used[i] == 1) {
- places = places + 1;
- }
- }
- System.out.println(places);
- for (int i = 0; i < N; i++) {
- for (int j = 0; j < depth[i].size(); j++) {
- System.out.print(depth[i].get(j) + " ");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement