Cod sursa(job #2675477)

Utilizator kitkat007Graphy kitkat007 Data 21 noiembrie 2020 20:24:28
Problema BFS - Parcurgere in latime Scor 40
Compilator java Status done
Runda Arhiva educationala Marime 2.23 kb
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();
                List<Integer> related = this.adjList.get(currNode);
                if (related != null) {
                    for (int neighbor : related) {
                        if (dist[neighbor] == UNREACHABLE_NODE) {
                            dist[neighbor] = dist[currNode] + 1;
                            queue.add(neighbor);
                        }
                    }
                }
            }
            return dist;
        }
    }

}