Cod sursa(job #1705868)

Utilizator FlorentinaPetcuFlorentina Petcu FlorentinaPetcu Data 21 mai 2016 00:56:46
Problema BFS - Parcurgere in latime Scor 90
Compilator java Status done
Runda Arhiva educationala Marime 1.88 kb

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Graph {
	int nodes;
	public Map<Integer, List<Integer>> adiacenta;
	int root;

	public Graph() {
		adiacenta = new HashMap<>();
	}

	public Graph(int nodes, Map<Integer, List<Integer>> edges) {
		this.nodes = nodes;
		this.adiacenta = edges;
	}

	public void readData(String filename) throws IOException {
		Scanner input = new Scanner(new FileReader(filename));
		nodes = input.nextInt();
		int M = input.nextInt();
		root = input.nextInt();

		for (int i = 1; i <= nodes; i++)
			adiacenta.put(i, new ArrayList<Integer>());

		int node1, node2;
		for (int i = 0; i < M; i++) {
			node1 = input.nextInt();
			node2 = input.nextInt();
			adiacenta.get(node1).add(node2);
		}
		input.close();
	}

}

public class Main {
	static int[] cost;

	public static void bsf(int s, Graph g) {
		int V = g.nodes;
		cost = new int[V + 1];

		for (int i = 1; i <= V; i++)
			cost[i] = -1;

		Queue<Integer> q = new LinkedList<>();
		q.add(s);
		cost[s] = 0;
		while (!q.isEmpty()) {
			int u = q.poll();

			for (int v = 0; v < g.adiacenta.get(new Integer(u)).size(); v++) {
				int n = g.adiacenta.get(new Integer(u)).get(v);
				if (cost[n] == -1) {
					q.add(new Integer(n));
					cost[n] = cost[u] + 1;
				}
			}
		}

	}

	public static void main(String[] args) throws IOException {
		Graph g = new Graph();
		g.readData("bfs.in");
		bsf(g.root, g);

		BufferedWriter write = new BufferedWriter(new FileWriter(new File("bfs.out")));
		for (int i = 1; i <= g.nodes; i++) {
			write.write(cost[i] + " ");
		}
		write.close();
	}
}