Cod sursa(job #2675470)

Utilizator kitkat007Graphy kitkat007 Data 21 noiembrie 2020 19:46:49
Problema BFS - Parcurgere in latime Scor 50
Compilator java Status done
Runda Arhiva educationala Marime 2.39 kb
import java.io.BufferedReader;
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 {
        BufferedReader br = new BufferedReader(new FileReader("bfs.in"));
        PrintWriter pw = new PrintWriter("bfs.out");
        String[] line = br.readLine().split(" ");
        int n = Integer.parseInt(line[0]);
        int m = Integer.parseInt(line[1]);
        int source = Integer.parseInt(line[2]);
        Graph g = new Graph(n);
        for (int i = 0; i < m; ++i) {
            line = br.readLine().split(" ");
            int from = Integer.parseInt(line[0]);
            int to = Integer.parseInt(line[1]);
            g.link(from, to);
        }
        br.close();
        int[] d = Solver.solve(g, source);
        for (int i = 1; i < d.length; ++i) {
            pw.print(d[i] + " ");
        }
        pw.close();
    }
}