Cod sursa(job #1836914)

Utilizator dianaa21Diana Pislaru dianaa21 Data 28 decembrie 2016 20:31:26
Problema BFS - Parcurgere in latime Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.84 kb
import java.util.*;
import java.io.*;

public class Main {

    private static int M, N, S;
    private static boolean[] visited;
    private static int[] distance;
    private static Vector<Vector<Integer>> V = new Vector<Vector<Integer>>();
    private static Queue<Integer> Q = new LinkedList<Integer>();

    public static void main(String[] args) throws FileNotFoundException {
        read();
        BFS();
        write();
    }

    private static void BFS() {
        int node, size, neighbour;
        while(Q.peek() != null) {
            node = Q.poll();
            visited[node] = true;
            size = V.get(node).size();
            for(int i = 0; i < size; ++i) {
                neighbour = V.get(node).get(i);
                if (!visited[neighbour]) {
                    Q.add(neighbour);
                    visited[neighbour] = true;
                    distance[neighbour] = distance[node] + 1;
                }
            }
        }
    }

    private static void read() throws FileNotFoundException {
        Scanner in = new Scanner(new File("bfs.in"));
        N = in.nextInt();
        M = in.nextInt();
        S = in.nextInt();

        for(int i = 0; i <= N; ++i)
            V.add(new Vector<Integer>());

        int x, y;
        for(int i = 1; i <= M; ++i) {
            x = in.nextInt();
            y = in.nextInt();
            if (x != y)
                V.get(x).add(y);
        }

        distance = new int[N+1];
        visited = new boolean[N+1];
        visited[S] = true;
        Q.add(S);
    }

    private static void write() throws FileNotFoundException {
        PrintWriter out = new PrintWriter("bfs.out");
        for(int i = 1; i <= N; ++i) {
            if (distance[i] == 0 && i != S)
                out.print("-1 ");
            else
                out.print(distance[i] + " ");
        }
        out.close();
    }
}