Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Breadth First Search

Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.

Input

In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.

Constraints

$1 \leq n \leq 100$

Output

For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1

4
1 2 2 4
2 1 4
3 0
4 1 3

Sample Output 1

1 0
2 1
3 2
4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in JAVA (judge verdict: Accepted)


import java.util.LinkedList;
import java.util.Scanner;
import java.util.Iterator;

class Graph {
	private int[] dist;
	private int[] visited;
	private int totalVertex;
	private LinkedList<LinkedList<Integer>> adjList;
	//adjacency list of edges
	public Graph() { totalVertex = 0; }
	public void loadAdjList() {
		Scanner in = new Scanner(System.in);
		totalVertex = in.nextInt();
		adjList = new LinkedList<LinkedList<Integer>>();
		dist = new int[totalVertex];
		for (int i = 0; i < dist.length; i++) {
			dist[i] = -1;
		}
		visited = new int[totalVertex];
		for (int j = 0; j < visited.length; j++) {
			visited[j] = 0;
		}
		for(int i = 0; i < totalVertex; i ++) {
			LinkedList<Integer> tmp = new LinkedList<Integer>();
			int idx1 = in.nextInt() - 1;
			int degree = in.nextInt();
			//System.out.println("mark idx1 = " + idx1 + " degree = " + degree);
			for(int j = 0; j < degree; j ++) {
				int idx2 = in.nextInt() - 1;
				tmp.add(idx2);
			}	
			adjList.add(tmp);
		}
		in.close();
	}
	public int[] BFS(int v) {
		LinkedList<Integer> toVisit = new LinkedList<Integer>();
		toVisit.add(v);
		visited[v] = 1;
		dist[v] = 0;
		while(!toVisit.isEmpty()) {
			int u = toVisit.remove();
		    for(int i = 0; i < adjList.get(u).size(); ++i) {
		    	int k = adjList.get(u).get(i);
		    	if (visited[k] == 0) {
		    		visited[k] = 1;
		    		toVisit.add(k);
		    		dist[k] = dist[u] + 1;
		    	}
		   
		    }
		   
		}
		for (int k = 0; k < dist.length; k++) {
		System.out.println(k+1 + " " + dist[k]);
		
	}
		return dist;
}
}
//change class name GraphRepresentation to Main() for submission to AIZU
public class Main {
	public static void main(String argv[]) {
		Graph g = new Graph();
		g.loadAdjList();
		int[] dist = g.BFS(0);
	}
}