Pagini recente » Monitorul de evaluare | Istoria paginii runda/mnmxmnmxmnmx_what | Cod sursa (job #3183549) | Cod sursa (job #3130350) | Cod sursa (job #1430816)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Main {
Node[] graph;
int nodesCount;
int edgesCount;
int source;
int[] distance;
Color[] color;
int[] parent;
public static enum Color {
WHITE,GREY,BLACK;
}
public class Node {
int a, b;
List<Integer> neighbors = new LinkedList<Integer>();
public Node(int a, int b) {
this.a = a;
this.b = b;
}
public void addNeighbor(int u) {
this.neighbors.add(u);
}
public List<Integer> getNeighbors() {
return neighbors;
}
}
public void bfs() {
Queue<Integer> queue = new LinkedList<>();
//initializari
for (int i = 0; i < nodesCount; i++) {
parent[i] = -1;
distance[i] = -1;
color[i] = Color.WHITE;
}
distance[source] = 0;
color[source] = Color.GREY;
queue.add(source);
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v : graph[u].getNeighbors()) {
System.out.println(v);
if (color[v] == Color.WHITE) {
distance[v] = distance[u] + 1;
parent[v] = u;
color[v] = Color.GREY;
queue.add(v);
}
}
System.out.println();
color[u] = Color.BLACK;
}
}
public void writeData() {
PrintWriter out = null;
try {
out = new PrintWriter("bfs.out");
for (int i = 0; i < nodesCount; i++) {
out.write(String.valueOf(distance[i]) + " ");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null ){
out.close();
}
}
}
public void readData() {
BufferedReader in;
try {
in = new BufferedReader(new FileReader("bfs.in"));
String line = in.readLine();
String[] tokens = line.split(" ");
nodesCount = Integer.valueOf(tokens[0]);
edgesCount = Integer.valueOf(tokens[1]);
source = Integer.valueOf(tokens[2]) - 1;
graph = new Node[nodesCount];
for (int i = 0; i < nodesCount; i++) {
graph[i] = new Node(0, 0);
}
parent = new int[nodesCount];
color = new Color[nodesCount];
distance = new int[nodesCount];
for (int i = 0; i < edgesCount; i++) {
line = in.readLine();
System.out.println(line);
tokens = line.split(" ");
int first = Integer.valueOf(tokens[0]) - 1;
int second = Integer.valueOf(tokens[1]) - 1;
graph[first].addNeighbor(second);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Main problem = new Main();
problem.readData();
problem.bfs();
problem.writeData();
}
}