Go: package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)
	nodes := make([]Node, n)

	for i := 0; i < n; i++ {
		nodes[i].list = make([]int, 0)
		nodes[i].d = -1
	}

	for i := 0; i < n; i++ {
		u := getNextInt(scanner)
		k := getNextInt(scanner)
		u--
		for ii := 0; ii < k; ii++ {
			v := getNextInt(scanner)
			v--
			nodes[u].list = append(nodes[u].list, v)
		}
	}

	queue := make([]int, n)
	queue[0] = 0
	nodes[0].d = 0
	d := 0
	i, j := 0, 1
	for i < j {
		d++
		prev := j
		for i < prev {
			for k, l := 0, len(nodes[queue[i]].list); k < l && i < n; k++ {
				if nodes[nodes[queue[i]].list[k]].d != -1 {
					continue
				}
				nodes[nodes[queue[i]].list[k]].d = d
				queue[j] = nodes[queue[i]].list[k]
				j++
			}
			i++
		}
	}

	for i := 0; i < n; i++ {
		fmt.Fprintln(writer, fmt.Sprintf("%d %d", i+1, nodes[i].d))
	}

	writer.Flush()
}

// Node ...
type Node struct {
	list []int
	d    int
}

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)