Cod sursa(job #3277879)

Utilizator costelus18Catalin Dohotaru costelus18 Data 17 februarie 2025 19:18:19
Problema BFS - Parcurgere in latime Scor 10
Compilator java Status done
Runda Arhiva educationala Marime 2 kb
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Main {
    int N;
    int M;
    int S;
    Map<Integer, List<Integer>> adjList = new HashMap<>();
    int[] distances;

    public static void main(String[] args) throws Exception {
        Main driver = new Main();
        driver.readInput();
        driver.solve();
        driver.writeOutput();
    }

    private void solve() {
        Queue<Integer> bfsQueue = new LinkedList<>();
        distances = new int[N + 1];
        Arrays.fill(distances, -1);
        int dist = 0;
        bfsQueue.add(S);
        while (!bfsQueue.isEmpty()) {
            int s = bfsQueue.size();
            for (int i = 0; i < s; i++) {
                int current = bfsQueue.remove();
                distances[current] = dist;
                for (int neigh: adjList.get(current)) {
                    if (distances[neigh] == -1)
                        bfsQueue.add(neigh);
                }
            }
            dist++;
        }
    }

    private void readInput() throws FileNotFoundException {
        File input = new File("bfs.in");
        Scanner sc = new Scanner(input);
        N = sc.nextInt();
        M = sc.nextInt();
        S = sc.nextInt();

        for (int i = 1; i <= M; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            if (adjList.containsKey(from))
                adjList.get(from).add(to);
            else {
                List<Integer> neighbors = new ArrayList<>();
                neighbors.add(to);
                adjList.put(from, neighbors);
            }
        }
    }

    private void writeOutput() throws IOException {
        PrintWriter writer = new PrintWriter("bfs.out", StandardCharsets.UTF_8);
        for (int i = 1; i <= N; i++) {
            writer.print(distances[i]);
            if (i < N)
                writer.print(" ");
        }
        writer.close();
    }
}