Go: package main

import "fmt"

type container struct {
	data []int
}

func (c *container) queue(v int) {
	c.data = append(c.data, v)
}
func (c *container) dequeue(p *int) bool {
	if p == nil || len(c.data) == 0 {
		return false
	}
	*p = c.data[0]
	c.data = c.data[1:len(c.data)]
	return true
}

func main() {
	var n int
	fmt.Scan(&n)
	g := make([][]int, n+1) // 1-indexed
	d := make([]int, n+1)   // 1-indexed
	for i := 1; i <= n; i++ {
		d[i] = -1
		var u, k, v int
		fmt.Scan(&u, &k)
		for j := 0; j < k; j++ {
			fmt.Scan(&v)
			g[u] = append(g[u], v)
		}
	}

	var q container
	d[1] = 0
	q.queue(1)

for len(q.data) > 0  { // 幅優先探索
		var v int
		q.dequeue(&v)
		for i := 0; i < len(g[v]); i++ {
			nv := g[v][i]
		if d[nv] == -1 { // 未訪問
				q.queue(nv)
				d[nv] = d[v] + 1
			}
		}
	}
	for i := 1; i <= n; i++ {
		fmt.Printf("%d %d\n", i, d[i])
	}
}

Python: from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def bfs(graph, initial):
    n = len(graph) - 1
    dist = [-1] * (n + 1)
    q = deque([initial])
    visited = [False] * (n + 1)
    visited[initial] = True
    dist[initial] = 0

    while len(q) != 0:
        edge = q.popleft()
        nxt = graph[edge]

        for i, e in enumerate(nxt):
            if visited[e] is False:
                q.append(e)
                dist[e] = dist[edge] + 1
                visited[e] = True

    return dist


def main():
    N = I()
    graph = [[] for i in range(N+1)]

    for i in range(N):
        a = LI()
        edge = a[0]
        if a[1] == 0:
            continue
        for e in a[2:]:
            graph[edge].append(e)
            # graph[e].append(edge)

    # print(graph)
    ret = bfs(graph, 1)
    for i in range(1, N+1):
        print(i, ret[i])


if __name__ == '__main__':
    main()

Python: import math
import copy
import sys
import fractions
# import numpy as np
# import statistics
import decimal
import heapq
import collections
import itertools
import bisect

# from operator import mul

sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputIntList():
    outputDataList = []
    inputData = input().split()
    outputDataList = [int(n) for n in inputData]

    return outputDataList


def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

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

d = [-1] * n

for a in adj:
    for i in range(len(a)):
        a[i] -= 1

s = 0
q = collections.deque([])
d[s] = 0
q.append(s)
while len(q):
    u = q.popleft()
    v = adj[u]
    for vi in v:
        if d[vi] == -1:
            d[vi] = d[u] + 1
            q.append(vi)
        elif d[vi] > d[u] + 1:
            d[vi] = d[u] + 1
            q.append(vi)

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

Python: n=int(input())
G=[[] for i in range(n)]
#G=[]
Q=[1]
d=[-1]*n
d[0]=0
visited=[False]*n
visited[0]=True

for i in range(n):
    arr=[int(x) for x in input().split()[2:]]
    for l in arr:
        G[i].append(l)
        #G[l-1].append(i+1)
    

kyori=0
while len(Q)!=0:
    
    #print(Q)
    #print(visited)
    v=Q.pop(0)
    
    for j in G[v-1]:
        if visited[j-1]:#次に行くところがすでに踏破済みだったら
            continue#更新しない
        else:
            d[j-1]=d[v-1]+1
            Q.append(j)
            visited[j-1]=True
for a in range(n):
    print(a+1,d[a])

Python: from sys import stdin
from collections import deque
n = int(stdin.readline())
M = [[0] * (n + 1) for _ in range(n + 1)]
d = [200] * (n + 1)
def bfs():
    d[1] = 0
    dq = deque()
    dq.append(1)
    while len(dq) > 0:
        u = dq.popleft()
        for v in range(1, n + 1):
            if M[u][v] == 0 or d[v] != 200: continue
            d[v] = d[u] + 1
            dq.append(v)
    for i in range(1, n + 1):
        print(i, (-1 if d[i] == 200 else d[i]))
for u in range(1, n + 1):
    U = [int(j) for j in stdin.readline().split()]
    for v in U[2:]:
        M[u][v] = 1
bfs()

Python: n = int(input())
adj = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
    l = list(map(int, input().split()))
    if l[1] == 0:
        continue 
    else:
        for j in range(2,len(l)):
            adj[l[0]-1][l[j]-1] = 1

color = ['white' for _ in range(n)]
d = [-1 for _ in range(n)]
color[0] = 'grey'
d[0] = 0
Q = [1]
while Q:
    u = Q.pop(0)
    color[u-1] = 'black'
    for v in range(1, n+1):
        if adj[u-1][v-1] == 1 and color[v-1] == 'white':
            Q.append(v)
            color[v-1] = 'grey'
            d[v-1] = d[u-1] + 1  

for i in range(n):
    print(' '.join([str(i+1), str(d[i])]))

Python: n = int(input())

m = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    com = list(map(int, input().split()))
    for j in range(com[1]):
        m[i][com[j+2]-1] = 1

color = ["white" for i in range(n)]

from collections import deque
queue = deque()

d = [-1 for i in range(n)]

def bfs():
    color[0] = "gray"
    d[0] = 0
    queue.append(0)
    while len(queue) != 0:
        u = queue.popleft()
        for i in range(n):
            if m[u][i] and color[i] == "white":
                color[i] = "gray"
                d[i] = d[u] + 1
                queue.append(i)
        color[u] = "black"

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

Python: import sys
input = sys.stdin.readline
from collections import deque

N = int(input())
G = [list(map(lambda x: int(x)-1, input().split()))[2:] for _ in range(N)]

D = [-1]*N
q = deque([[0, 0]])
while q:
    cur, dis = q.popleft()
    if D[cur] != -1: continue
    D[cur] = dis
    for nex in G[cur]:
        q.append([nex,dis+1])
for i in range(N):
    print(i+1, D[i])

Python: # -*- coding: utf-8 -*-
"""
Created on Sat Apr  6 11:50:13 2019

@author: Yamazaki Kenichi
"""
from collections import deque

n = int(input())
A = [[]] + [list(map(int,input().split())) for i in range(n)]

#B = [[0 for i in range(n+1)] for i in range(n+1)]
#for i in range(1,n+1):
#    for j in range(A[i][1]):
#        B[i][A[i][j+2]] = 1

T = [[-1, -1] for i in range(n+1)]
T[1][0], T[1][1] = 1, 0
q = deque([1])
def dfs():
    global depth
    while len(q) > 0:
        for i in range(A[q[0]][1]):
            if T[A[q[0]][i+2]][0] == -1:
                q.append(A[q[0]][i+2])
                T[q[-1]][0] = 1
                T[q[-1]][1] = T[q[0]][1] + 1
        q.popleft()
dfs()
for i in range(1,n+1):
    print(i,T[i][1])