Cod sursa(job #1705861)

Utilizator FlorentinaPetcuFlorentina Petcu FlorentinaPetcu Data 21 mai 2016 00:45:10
Problema BFS - Parcurgere in latime Scor 30
Compilator java Status done
Runda Arhiva educationala Marime 2.69 kb

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

import java.io.BufferedReader;
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;
import java.util.StringTokenizer;

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 {
		BufferedReader read = new BufferedReader(new FileReader(new File(filename)));
		StringTokenizer tokens = new StringTokenizer("");

		List<Integer> node;

		tokens = new StringTokenizer(read.readLine());

		nodes = Integer.parseInt(tokens.nextToken());

		for (int i = 0; i <= nodes; i++) {
			node = new ArrayList<>();
			node.add(i);
		}

		int M = Integer.parseInt(tokens.nextToken());
		root = Integer.parseInt(tokens.nextToken());

		for (int i = 0; i < M; i++) {
			tokens = new StringTokenizer(read.readLine());
			int u = Integer.parseInt(tokens.nextToken());
			int v = Integer.parseInt(tokens.nextToken());
			if (adiacenta.containsKey(u)) {
				List<Integer> nod = adiacenta.get(u);
				nod.add(v);
				adiacenta.put(u, nod);
			} else {
				List<Integer> nodu = new ArrayList<>();
				nodu.add(v);
				adiacenta.put(u, nodu);
			}
			// if (adiacenta.containsKey(v)) {
			// List<Integer> nod = adiacenta.get(v);
			// nod.add(u);
			// adiacenta.put(v, nod);
			// } else {
			// List<Integer> nodv = new ArrayList<>();
			// nodv.add(u);
			// adiacenta.put(v, nodv);
			// }

		}

		read.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();
	}
}