Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.sun.jmx.remote.internal.ArrayQueue;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.StringTokenizer;
- /**
- * Created with IntelliJ IDEA.
- * User: yulya3102
- * Date: 23.10.12
- * Time: 16:54
- * To change this template use File | Settings | File Templates.
- */
- public class A {
- public static void main(String[] args) throws IOException {
- BufferedReader in = new BufferedReader(new FileReader("pathbge1.in"));
- StringTokenizer str = new StringTokenizer(in.readLine());
- int n = Integer.parseInt(str.nextToken());
- int m = Integer.parseInt(str.nextToken());
- Graph graph = new Graph(n);
- for (int i = 0; i < m; i++) {
- str = new StringTokenizer(in.readLine());
- int from = Integer.parseInt(str.nextToken()) - 1;
- int to = Integer.parseInt(str.nextToken()) - 1;
- graph.add(from, to);
- }
- int[] d = graph.bfs(0);
- PrintWriter out = new PrintWriter(new File("pathbge1.out"));
- for (int i = 0; i < n; i++)
- out.print(d[i] + " ");
- out.close();
- }
- private static class Graph {
- class AdjacencyList {
- private ArrayList<Integer> list;
- public AdjacencyList() {
- list = new ArrayList<Integer>();
- }
- public int size() {
- return list.size();
- }
- public void add(int to) {
- list.add(to);
- }
- public int get(int index) {
- return list.get(index);
- }
- }
- AdjacencyList[] adjacencyLists;
- int n;
- int d[];
- ArrayQueue<Integer> queue;
- public Graph(int n) {
- this.n = n;
- d = new int[n];
- adjacencyLists = new AdjacencyList[n];
- for (int i = 0; i < n; i++) {
- d[i] = Integer.MAX_VALUE;
- adjacencyLists[i] = new AdjacencyList();
- }
- queue = new ArrayQueue<Integer>(n);
- }
- public void add(int from, int to) {
- adjacencyLists[from].add(to);
- adjacencyLists[to].add(from);
- }
- public int[] bfs(int s) {
- d[s] = 0;
- queue.add(s);
- while (!queue.isEmpty()) {
- int u = queue.remove(0);
- for (int i = 0; i < adjacencyLists[u].size(); i++) {
- int v = adjacencyLists[u].get(i);
- if (d[v] == Integer.MAX_VALUE) {
- d[v] = d[u] + 1;
- queue.add(v);
- }
- }
- }
- return d;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment