Pagini recente » Cod sursa (job #3351338) | Cod sursa (job #1576149) | Cod sursa (job #1093527) | Cod sursa (job #2033020) | Cod sursa (job #1705648)
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Bfs {
static Map<Integer, List<Integer>> graph;
static int dist[];
static boolean visited[];
static final int AVAILABLE = -1;
static void bfs(int s) {
dist[s] = 0;
visited[s] = true;
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
while (!q.isEmpty()) {
Integer u = q.poll();
List<Integer> uSucc = graph.get(u);
for (Integer v : uSucc) {
if (!visited[v]) {
dist[v] = dist[u] + 1;
q.add(v);
}
}
visited[u] = true;
}
}
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(new FileReader("bfs.in"));
int N = input.nextInt(),
M = input.nextInt(),
S = input.nextInt();
graph = new HashMap<>();
visited = new boolean[N + 1];
dist = new int[N + 1];
for (int i = 0; i < N; i++)
dist[i] = -1;
int node1, node2;
for (int i = 0; i < M; i++) {
node1 = input.nextInt();
node2 = input.nextInt();
if(!graph.containsKey(node1))
graph.put(node1, new ArrayList<Integer>());
graph.get(node1).add(node2);
}
input.close();
bfs(S);
PrintWriter output = new PrintWriter("bfs.out");
for (int i = 1; i < N + 1; i++) {
output.print(dist[i] + " ");;
}
output.close();
}
}