Pagini recente » Cod sursa (job #1082355) | Rating david roxana (DavidRoxana1999) | Cod sursa (job #1646319) | Istoria paginii runda/saptamana_altfel_6d | Cod sursa (job #2675468)
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class Main {
static class Graph {
private final int nodesCount;
private final Map<Integer, List<Integer>> linksMap = new HashMap<>();
public Graph(int n) {
this.nodesCount = n;
}
public void link(int a, int b) {
linksMap.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
}
public List<Integer> getRelated(Integer currNode) {
return linksMap.get(currNode);
}
public int getNodesCount() {
return nodesCount;
}
}
static class Solver {
public static int[] solve(Graph g, int source) {
int[] dist = new int[g.getNodesCount() + 1];
Arrays.fill(dist, -1);
dist[source] = 0;
Queue<Integer> queue = new ArrayDeque<>();
queue.add(source);
while (!queue.isEmpty()) {
Integer currNode = queue.poll();
List<Integer> relatedNodes = g.getRelated(currNode);
if (relatedNodes != null) {
int currDist = dist[currNode] + 1;
relatedNodes.forEach(node -> {
if (dist[node] == -1) {
dist[node] = currDist;
queue.add(node);
}
});
}
}
return dist;
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new FileReader("bfs.in"));
PrintWriter pw = new PrintWriter("bfs.out");
int n = sc.nextInt();
int m = sc.nextInt();
int source = sc.nextInt();
Graph g = new Graph(n);
for (int i = 0; i < m; ++i) {
int from = sc.nextInt();
int to = sc.nextInt();
g.link(from, to);
}
sc.close();
int[] d = Solver.solve(g, source);
for (int i = 1; i < d.length; ++i) {
pw.print(d[i] + " ");
}
pw.close();
}
}