Pagini recente » Cod sursa (job #2473025) | Cod sursa (job #2297302) | Cod sursa (job #2002960) | Cod sursa (job #1575045) | Cod sursa (job #1259086)
import java.io.*;
import java.util.*;
public class Bfs {
private ArrayList<LinkedList<Integer>> edges;
private int n, m, S;
private BufferedReader in;
private BufferedWriter out;
private int[] sol;
public static void main(String[] args) throws IOException {
new Bfs();
}
public Bfs() throws IOException {
in = new BufferedReader(new FileReader("bfs.in"));
out = new BufferedWriter(new FileWriter("bfs.out"));
edges = new ArrayList<LinkedList<Integer>>();
readData();
bfs();
printSolution();
}
public void bfs() {
int node, neighb;
boolean[] VIS = new boolean[n + 1];
Queue<Integer> myQueue = new PriorityQueue<Integer>();
myQueue.add(S);
VIS[S] = true;
while (!myQueue.isEmpty()) {
node = myQueue.poll();
for (int i=0;i<edges.get(node).size();++i) {
neighb = edges.get(node).get(i);
if (!VIS[neighb]) {
myQueue.add(neighb);
sol[neighb] = sol[node] + 1;
}
}
}
}
public void initSolution() {
sol = new int[n + 1];
for (int i=0;i<n;++i) {
sol[i] = 0;
}
}
public void printSolution() throws IOException {
for (int i=1;i<=n;++i) {
if (sol[i] == 0 && i != S) {
out.write("-1 ");
}
else {
out.write(sol[i] + " ");
}
}
out.flush();
}
public void readData() throws IOException {
int a, b;
String[] line = in.readLine().split(" ");
n = Integer.parseInt(line[0]);
m = Integer.parseInt(line[1]);
S = Integer.parseInt(line[2]);
for (int i=0;i<=n;++i) {
edges.add(new LinkedList<Integer>());
}
initSolution();
for (int i=0;i<m;++i) {
line = in.readLine().split(" ");
a = Integer.parseInt(line[0]);
b = Integer.parseInt(line[1]);
edges.get(a).add(b);
}
}
}