Pagini recente » Monitorul de evaluare | Profil Cristian12354 | Cod sursa (job #1298048) | tenis | Cod sursa (job #2090143)
import java.io.*;
import java.util.*;
public class Main {
private static final String INPUT_FILE_PATH = "bfs.in";
private static final String OUTPUT_FILE_PATH = "bfs.out";
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader(INPUT_FILE_PATH));
PrintWriter out = new PrintWriter(OUTPUT_FILE_PATH);
int n = in.nextInt();
int m = in.nextInt();
int root = in.nextInt();
DirectedGraph mGraph = new DirectedGraph(n);
while (m-- > 0) {
int source = in.nextInt();
int dest = in.nextInt();
mGraph.addEdge(source, dest);
}
int[] dist = mGraph.getDistancesFrom(root);
for (int i = 1; i <=n; ++i) {
out.print(dist[i] + " ");
}
out.flush();
in.close();
out.close();
}
static class DirectedGraph {
private static final int UNREACHABLE_NODE = -1;
private List<List<Integer>> adjList;
private int cntNodes;
public DirectedGraph(int n) {
this.cntNodes = n;
this.adjList = new ArrayList<>();
for (int i = 0; i <= n; ++i) {
this.adjList.add(new ArrayList<Integer>());
}
}
public void addEdge(int source, int dest) {
this.adjList.get(source).add(dest);
}
public int[] getDistancesFrom(int root) {
int[] dist = new int[this.cntNodes + 1];
Arrays.fill(dist, UNREACHABLE_NODE);
dist[root] = 0;
Queue<Integer> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
int currNode = queue.poll();
for (int neighbor : this.adjList.get(currNode)) {
if (dist[neighbor] == UNREACHABLE_NODE) {
dist[neighbor] = dist[currNode] + 1;
queue.add(neighbor);
}
}
}
return dist;
}
}
}