Cod sursa(job #1704384)

Utilizator DrumeaDADrumea Diana DrumeaDA Data 18 mai 2016 18:33:23
Problema BFS - Parcurgere in latime Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.13 kb
//package BFS;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class Graph {

	int numNodes;
	int numEdges;
	int source;
	List<List<Integer>> edges = new ArrayList<>();
	
	public int BFS(int dest){
		List<Integer> q = new ArrayList<Integer>();
		int cost = 0;
		int[] visited = new int[numNodes + 1];
		int[] costs = new int[numNodes + 1];
		
		for(int i = 0 ; i <= numNodes ; i++){
			visited[i] = 0;
			costs[i] = 0;
		}
		
		q.add(source);
		visited[source] = 1;
		
		while(!q.isEmpty()){
			int node = q.remove(0);
			
			if(node == dest){
				return costs[dest];
			}
			
			for(Integer i : edges.get(node)){
				if(visited[i] == 0){
					visited[i] = 1;
					costs[i] = costs[node] + 1;
					q.add(i);
				}
			}
		}
		return -1;
	}

	public static void main(String[] args) throws FileNotFoundException {
		BufferedReader br = new BufferedReader(new FileReader("bfs.in"));
		int src, dest;
		String line;
		String[] strings;

		try {
			line = br.readLine();
			if (line == null) {
				return;
			}
			Graph g = new Graph();
			strings = line.trim().split("\\s+");
			g.numNodes = Integer.parseInt(strings[0]);
			g.numEdges = Integer.parseInt(strings[1]);
			g.source = Integer.parseInt(strings[2]);

			for (int i = 0; i <= g.numNodes; i++) {
				g.edges.add(new ArrayList<>());
			}

			for (int i = 0; i < g.numEdges; i++) {
				line = br.readLine();
				if (line == null) {
					return;
				}
				strings = line.trim().split("\\s+");
				src = Integer.parseInt(strings[0]);
				dest = Integer.parseInt(strings[1]);
				g.edges.get(src).add(new Integer(dest));
			}
			br.close();
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File("bfs.out")));
			
			for(int i = 1 ; i <= g.numNodes ; i++){
				String toWrite = "" + g.BFS(i);
				bw.write(toWrite + " ");
			}
			bw.close();
			
		} catch (IOException e) {
			
		}
	}
}