Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

//util
var sc = bufio.NewScanner(os.Stdin)

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const INFTY = (1 << 21)
const MAX = 100
const WHITE = 0
const GRAY = 1
const BLACK = 2

var time, n int

//隣接行列
var M [MAX][MAX]int

//d[i]: 頂点1から頂点iまでの距離
var color, d [MAX]int

func bfs(s int) {
	var q []int
	q = append(q, s)
	for i := 0; i < n; i++ {
		d[i] = INFTY
	}
	//sは開始点なので、0をいれる
	d[s] = 0

	//キューが空になるまで、以下を繰り返す
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		for v := 0; v < n; v++ {
			if M[u][v] == 0 {
				continue
			}
			if d[v] != INFTY {
				continue
			}
			d[v] = d[u] + 1
			q = append(q, v)
		}
	}

	for i := 0; i < n; i++ {
		fmt.Printf("%d ", i+1)
		if d[i] == INFTY {
			fmt.Printf("%d\n", -1)
		} else {
			fmt.Printf("%d\n", d[i])
		}
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n = nextInt()
	for i := 0; i < n; i++ {
		u, k := nextInt(), nextInt()
		M[u-1][u-1] = 0

		//fmt.Println(u, k)
		if k > 0 {
			for j := 0; j < k; j++ {

				v := nextInt()
				M[u-1][v-1] = 1

			}
		}

	}

	bfs(0)

}

Python: import abc


class AdjacentGraph:
    """Implementation adjacency-list Graph.
    Beware ids are between 1 and size.
    """
    def __init__(self, size):
        self.size = size
        self._nodes = [[0] * (size+1) for _ in range(size+1)]

    def set_adj_node(self, id_, adj_id):
        self._nodes[id_][adj_id] = 1

    def __iter__(self):
        self._id = 0
        return self

    def __next__(self):
        if self._id < self.size:
            self._id += 1
            return (self._id, self._nodes[self._id][1:])

        raise StopIteration()

    def dfs(self, handler=None):
        def find_first():
            try:
                return visited.index(0)
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        depth = 0
        while first is not None:
            stack = [(first, depth, 0)]
            while len(stack) > 0:
                i, depth, j = stack.pop()
                if j == 0:
                    if handler:
                        handler.visit(i, depth)
                    visited[i-1] = 1
                    yield i
                try:
                    j = self._nodes[i].index(1, j+1)
                    stack.append((i, depth, j))
                    if visited[j-1] == 0:
                        stack.append((j, depth+1, 0))
                except ValueError:
                    if handler:
                        handler.leave(i)
            first = find_first()

    def bfs(self, handler=None):
        def find_first():
            try:
                return visited.index(0)
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        depth = 0
        while first is not None:
            queue = [(first, depth)]
            while len(queue) > 0:
                (i, depth), *queue = queue
                if visited[i-1] == 0:
                    if handler:
                        handler.visit(i, depth)
                    visited[i-1] = 1
                    yield i
                else:
                    continue
                j = 0
                while j < self.size:
                    try:
                        j = self._nodes[i].index(1, j+1)
                        queue.append((j, depth+1))
                    except ValueError:
                        break
                if handler:
                    handler.leave(i)
            first = find_first()


class EventHandler(abc.ABC):
    @abc.abstractmethod
    def visit(self, i, depth):
        pass

    @abc.abstractmethod
    def leave(self, i):
        pass


class Logger(EventHandler):
    def __init__(self, n):
        self.log = [(0, 0)] * n
        self.step = 0

    def visit(self, i, depth):
        self.step += 1
        self.log[i-1] = (self.step, depth, 0)

    def leave(self, i):
        self.step += 1
        self.log[i-1] = (self.log[i-1][0], self.log[i-1][1], self.step)

    def by_node(self):
        i = 1
        for discover, depth, finish in self.log:
            yield (i, discover, depth, finish)
            i += 1

def run():
    n = int(input())
    g = AdjacentGraph(n)
    log = Logger(n)

    for i in range(n):
        id_, c, *links = [int(x) for x in input().split()]
        for n in links:
            g.set_adj_node(id_, n)

    for i in g.bfs(log):
        pass

    for node in log.by_node():
        id_, find, dep, exit = node
        print("{} {}".format(id_, dep))


if __name__ == '__main__':
    run()

Python: from __future__ import print_function
import time
from sys import stdin
from Queue import Queue
start = time.clock()
i = 0
num=int(stdin.readline())
L=[]
for _ in range(num):
    L.append([int(s) for s in stdin.readline().split()[2:]])
 
d=[-1]*num
d[0]=0
q=Queue(100)
q.put(0)
while not q.empty():
    u=q.get()
    for v in L[u]:
        if d[v-1]<0:
            d[v-1]=d[u]+1
            q.put(v-1)
for i,v in enumerate(d):
    print (i+1,)

Python: from collections import deque

N = int(input())

edge = [[] for _ in range(N)]
for _ in range(N):
    t = list(map(int,input().split()))
    if t[1] != 0:
        edge[t[0]-1] = list(map(lambda x:int(x)-1, t[2:]))

dist = [-1]*N
dist[0] = 0
        
q = deque([0])
while q:
    now = q.popleft()
    for nxt in edge[now]:
        if dist[nxt] == -1:
            dist[nxt] = dist[now] + 1
            q.append(nxt)
        else:
            dist[nxt] = min(dist[nxt], dist[now] + 1)

for i,d in enumerate(dist):
    print(i+1, d)

Python: import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy

def bfs(start):
    d = [-1]*n
    d[start] = 0
    q = collections.deque([start])
    while q:
        p = q.popleft()
        next_v = edge[p]
        for v in next_v:
            if d[v] == -1:
                q.append(v)
                d[v] = d[p] + 1
    return d

if __name__ == "__main__":
    n = int(input())
    edge = []
    for i in range(n):
        u,k,*v_li = map(int,input().split())
        u-=1
        for j in range(len(v_li)):
            v_li[j] -= 1
        edge.append(v_li)
    ans = bfs(0)
    for i in range(n):
        print(i+1,ans[i])

Python: # -*- coding: utf_8 -*-

level = False
def debug(v):
    if level:
        print(v)

NOT_FOUND = 0
ENQUEUED = 1
FOUND = 2

def bfs(graph, status, results):
    queue = []
    queue.append(1)
    while len(queue) != 0:
        node = queue.pop(0)
        status[node] = FOUND
        d = results[node]
        for edge in graph[node]:
            if status[edge] != NOT_FOUND:
                continue
            status[edge] = ENQUEUED
            queue.append(edge)
            results[edge] = d + 1

    return results

if __name__ == "__main__":
    n = int(input())
    status = [NOT_FOUND] * (n + 1)
    results = [-1] * (n + 1)
    results[1] = 0
    g = [[0]]

    for i in range(n):
        row = [int(x) for x in input().split()]
        row.pop(0)
        row.pop(0)
        g.append(row)

    bfs(g, status, results)
    results.pop(0)

    print(results)
    for idx, v in enumerate(results):
        print(idx + 1, v)