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: Wrong Answer)


import java.util.*;


public class Main{ 

	public static void main(String args[]){
		Scanner scan = new Scanner(System.in);
		AdjacencyMatrices am = new AdjacencyMatrices(scan.nextInt());
		am.readList(scan);
		Graph graph = new Graph(am.getMatrix());
		//graph.walk();
		graph.nearest();
	}

}
class Graph{
	ArrayList<Node> vertices;
	public Graph(int[][] matrix){
		vertices = new ArrayList<Node>();
		for(int i=0; i<matrix.length;i++)
			vertices.add(new Node(i+1));
		for(int i=0; i<matrix.length;i++)
			for(int j=0; j<matrix.length; j++)
				if(matrix[i][j]!=0)
					vertices.get(i).addNext(vertices.get(j));
	}
	void walk(){
		int time = 0;
		for(int i=0; i<vertices.size();i++){
			time = vertices.get(i).walk(time);
		}
	}
	void nearest(){
		
		for(int i=0; i<vertices.size();i++){
			clearHistory();
			ArrayDeque<Node> queue = new ArrayDeque<Node>();
			queue.addFirst(vertices.get(0));
			System.out.println( (i+1) +" "+vertices.get(0).bfs(queue, 0, i+1));
		}
	}
	void clearHistory(){
		for(int i=0; i<vertices.size();i++)
					vertices.get(i).disSteped();	
	}
	void print(){

		for(int i=0; i<vertices.size();i++)
			vertices.get(i).result();
	}
}

class Node{
	int id;
	int startTime;
	int endTime;
	boolean steped = false;
	ArrayList<Boolean> stepedNext = new ArrayList<Boolean>(); 
	ArrayList<Node> nextNode = new ArrayList<Node>();
	public Node(int id){
		this.id = id;
	}
	public void addNext(Node n){
		nextNode.add(n);
		stepedNext.add(false);
	}
	public void disSteped(){
		this.steped = false;
	}
	public int bfs(ArrayDeque<Node> queue, int step, int target){
		Node node = queue.removeLast();

		//System.out.println("bfs_id : " + node.id);
		node.steped = true;
		if(node.id == target){
			//System.out.println("find");
			return 0;
		}
		for(Node n : node.nextNode)
			if(!n.steped)
				queue.addFirst(n);
		for(Node n : node.nextNode){
			
			if(!n.steped){
				//System.out.println("bfs, id :  " + n.id + ", steped : "+ n.steped);
				int temp = n.bfs(queue, step + 1, target);
			
				if(temp >=0 ){
					//System.out.println("gt 0");
					return temp+1;
				}else{
					//System.out.println("-1");
				}
			}
		}
		return -1;
	}
	public int walk(int time){
		if(this.steped)
			return time;
		time++;//
		this.startTime = time;
		this.steped = true;
		int end = time;
		for(int i=0; i<stepedNext.size(); i++){
			time = nextNode.get(i).walk(time);
		}
		time++;//
		this.endTime = time;
		return endTime;
	}
	boolean remainNext(){
		return stepedNext.contains(false);
	}
	void result(){
		System.out.println(this.id + " " + startTime + " " + endTime);
	}
}
class AdjacencyMatrices{
	int pointNum;
	int[][] matrix;
	public AdjacencyMatrices(int n){
		pointNum = n;
		matrix = new int[n][];
		for(int i=0; i<n; i++)
			matrix[i] = new int[n];
	}
	public void readList(Scanner scan){
		for(int i=0; i<pointNum; i++){
			int index = scan.nextInt()-1;
			int dim = scan.nextInt();
			for(int j=0; j< dim; j++)
				matrix[index][scan.nextInt()-1] = 1;
		}
	}
	public int[][] getMatrix(){
		return matrix;
	}
	public void printMatrix(){
		StringBuilder temp = new StringBuilder();
		for(int i=0; i<pointNum; i++){
			for(int j=0; j<pointNum; j++){
				temp.append(matrix[i][j]);
				if(j!=pointNum-1)
					temp.append(" ");
			}
			temp.append("\n");
		}
		System.out.print(new String(temp));
	}

}