Go: package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

const (
	N     = 100
	INFTY = 1 << 21
)

type Graph struct {
	M [N][N]int
	d [N]int
}

func (g *Graph) bfs(s, n int) string {
	var q []int
	q = append(q, s) // push

	for i := 0; i < n; i++ {
		g.d[i] = INFTY
	}
	g.d[s] = 0

	for len(q) != 0 {
		u := q[0]
		q = q[1:] // pop
		for v := 0; v < n; v++ {
			if g.M[u][v] == 0 || g.d[v] != INFTY {
				continue
			}
			g.d[v] = g.d[u] + 1
			q = append(q, v) // push
		}
	}

	var out bytes.Buffer
	for i := 0; i < n; i++ {
		if g.d[i] == INFTY {
			out.WriteString(fmt.Sprintf("%d -1\n", i+1))
			continue
		}
		out.WriteString(fmt.Sprintf("%d %d\n", i+1, g.d[i]))
	}

	return strings.TrimRight(out.String(), "\n")
}

func answer(reader io.Reader) string {
	sc := bufio.NewScanner(reader)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())

	var g Graph
	for i := 0; i < n; i++ {
		sc.Scan()
		u, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		k, _ := strconv.Atoi(sc.Text())
		u--
		for j := 0; j < k; j++ {
			sc.Scan()
			v, _ := strconv.Atoi(sc.Text())
			v--
			g.M[u][v] = 1
		}
	}

	return g.bfs(0, n)
}

func main() {
	fmt.Println(answer(os.Stdin))
}

Python: from collections import deque

def bfs(adj_mat, d):
    Q = deque()
    N = len(d)
    color = ["W" for n in range(N)]

    Q.append(0)
    d[0] = 0

    while len(Q) != 0:
        u = Q.popleft()

        for i in range(N):
            if adj_mat[u][i] == 1 and color[i] == "W":
                color[i] = "G"
                d[i] = d[u] + 1
                Q.append(i)

        color[u] = "B"

    for i in range(N):
        if color[i] != "B":
            d[i] = -1

def Main():
    N = int(input())

    adj_mat = [[0 for n in range(N)] for n in range(N)]
    d = [0] * N

    for n in range(N):
        u, k , *V = map(int, input().split())

        if k > 0:
            for i in V:
                adj_mat[n][i - 1] = 1

    bfs(adj_mat, d)

    for n in range(N):
        print("{} {}".format(n + 1, d[n]))
Main()

Python: if __name__ == '__main__':
    from sys import stdin
    input = stdin.readline

    from collections import deque, defaultdict
    from copy import deepcopy

    INFTY = -1   # 探索しなかったやつを-1としてprintしやすくするために-1とした。

    n = int(input())

    M = [[0]*n for _ in range(n)]

    def bfs(s):
        q = deque()
        q.append(s)
        d = [INFTY]*n
        d[s] = 0
        while q: # qが空だとwhileループから抜ける
            u = q.popleft()  # pythonのdequeはpopleft関数で戻り値がpopした要素になる
            for v in range(n):
                if M[u][v] == 0:
                    continue
                if d[v] != INFTY:
                    continue
                d[v] = d[u] + 1
                q.append(v)
        for i in range(n):
            print(str(i+1) + ' ' + str(d[i]))

    for _ in range(n):
        u, k, *vv = map(int, input().split())
        u -= 1
        for v in vv:
            v -= 1
            M[u][v] = 1

    bfs(0)

Python: from sys import stdin
from collections import deque
n = int(input())
d = [-1] * (n + 1)
def bfs():
    d[1] = 0
    dq = deque([1])
    while len(dq) != 0:
        v = dq.popleft()
        for c in G[v]:
            if d[c] != -1 : continue
            d[c] = d[v] + 1
            dq.append(c)
    for i, x in enumerate(d[1:], start=1):
        print(i, x)
G = [0] + [list(map(int, input().split()[2:])) for _ in range(n)]
bfs()

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)