Pagini recente » Cod sursa (job #2305549) | Cod sursa (job #2352879) | Cod sursa (job #2529958) | Cod sursa (job #1667117) | Cod sursa (job #1836914)
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();
}
}