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) + 1
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        while first is not None:
            stack = [(first, 0, 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) + 1
            except ValueError:
                return None

        visited = [0] * self.size
        first = 1
        while first is not None:
            queue = [(first, 0)]
            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
                try:
                    j = 0
                    while j < self.size:
                        j = self._nodes[i].index(1, j+1)
                        if visited[j-1] == 0:
                            queue.append((j, depth+1))
                except ValueError:
                    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
        if id_ > 1 and dep == 0:
            dep = -1
        print("{} {}".format(id_, dep))


if __name__ == '__main__':
    run()

Python: #import pysnooper
#import os,re,sys,operator,math,heapq,string
from collections import Counter,deque
#from operator import itemgetter
#from itertools import accumulate,combinations,groupby,combinations_with_replacement
from sys import stdin,setrecursionlimit
#from copy import deepcopy
setrecursionlimit(10**6)
input=stdin.readline

n=int(input().rstrip())
gragh=[[] for _ in range(n)]
q=deque()
for i in range(n):
    u=list(map(int,input().rstrip().split()))
    for j in u[2:]:
        gragh[u[0]-1].append(j-1)
#print(gragh)
dis=[-1]*n
dis[0]=0
q.append(0)
while len(q)!=0:
    v=q.popleft()
    for i in gragh[v]:
        if dis[i]!=-1:
            continue
        dis[i]=dis[v]+1
        q.append(i)
for i,j in enumerate(dis,1):
    print(i,j)

Python: from collections import deque
n = int(input())
A = [0]*(n+1)
D = [-1]*(n+1)
DP = [0]*(n+1)
d = deque()
for i in range(n):
    A[i+1] = [int(i) for i in input().split()]
d.append(1)
D[1] = 0
DP[1] = 0
while(len(d)>0):
    tmp = d.pop()
    for i in A[tmp][2:]:
        if not DP[i]:
            D[i] = D[tmp]+1
            DP[i] = 1
            d.appendleft(i)
for i in range(1,n+1):
    tmp = "{} {}".format(i,D[i])
    print(tmp)

Python: N= int(input())
E = [input().split()[2:] for _ in range(N)]
Q = [0]
L = [0] + [-1]*N
def func(ide):
    global Q
    for i in E[ide]:
        i = int(i) - 1
        if L[i] < 0 :L[i] = L[ide] +1 ;Q.append(i)
    

while Q:top = Q.pop(0);func(top)

for i in range(N):print(i + 1 ,int(L[i]))

Python: import queue

n = int(input())

adj = [ [] for _ in range (n) ]

for i in range(n):
    _, _, *adj[i] = list(map(int, input().split()))

q = queue.Queue()

d = [-1] * n
flag = [0] * n

q.put(1)
d[0] = 0
flag[0] = 1

while not q.empty():
    u = q.get()

    for v in adj[u-1]:
        if flag[v-1] == 0:
            flag[v-1] = 1
            d[v-1] = d[u-1] + 1
            q.put(v)

for i in range(n):
    print(i+1, d[i])

Python: from collections import deque
n = int(input())
Ps = []
for _ in range(n):
  lis = list(map(int, input().split()))
  if len(lis)>2:
    Ps.append(lis[2:])
  else:
    Ps.append([])
ans = [-1]*n
ans[0] = 0
queue = deque()
checked = deque()
[queue.append([p, 1]) for p in Ps[0]]
checked.append(1)
while queue:
  t, pa = queue.popleft()
  if not t in checked:
    for i in Ps[t-1]:
      queue.append([i, t])
    ans[t-1] = ans[pa-1]+1
    checked.append(t)
for i, a in enumerate(ans):
  print(i+1, a)