Go: package main

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

const MAX = 1000
const NIL = -1

type Node struct {
	id    int
	depth int
}

type Queue struct {
	head      int
	tail      int
	container [MAX]Node
}

func (q *Queue) inQueue(x Node) {
	q.container[q.tail] = x
	q.tail = (q.tail + 1) % MAX
}

func (q *Queue) deQueue() Node {
	x := q.container[q.head]
	q.head = (q.head + 1) % MAX
	return x
}

func (q *Queue) isEmpty() bool {
	return q.head == q.tail
}

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

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

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInt()
	route := make([][]int, n)
	for i := range route {
		u, k := scanInt(), scanInt()
		u--
		route[u] = make([]int, k)
		for j := range route[u] {
			num := scanInt()
			num--
			route[i][j] = num
		}
	}

	d := make([]int, n)
	for i := range d {
		d[i] = NIL
	}

	start := Node{0, 0}
	que := Queue{}
	que.inQueue(start)
	for !que.isEmpty() {
		node := que.deQueue()
		if d[node.id] != NIL {
			continue
		}
		d[node.id] = node.depth

		for _, nextId := range route[node.id] {
			next := Node{id: nextId, depth: node.depth + 1}
			que.inQueue(next)
		}
	}

	for i, depth := range d {
		fmt.Println(i+1, depth)
	}
}

Python: n = int(input())
g = [input().split()[2:] for _ in range(n)]

from collections import deque
que = deque()
que.append(0)
d = [0] + [-1] * n

while que:
    u = que.popleft()

    for v in g[u]:
        v = int(v) - 1

        if d[v] < 0:
            d[v] = d[u] + 1
            que.append(v)

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

"""
・グラフの数を受け取る
・グラフを作る．今回は隣接リストで必要な部分だけを残してリスト化する
・キュー用の配列を作る（これはなんでもいい．普通のリストでも可）．そのキューには1番初めのスタート位置を入れておく
・最短距離を置いておくリストを用意
・queの中身がなくなるまで続ける
・queの中身を取り出して，それにくっついてるノードを全て舐めていく．int方で入力を受け取っていないから注意．1-indexを0-indexに変える．
・もしそこにまだBFSが訪れていなかったら，そこに前回の場所から1足した物を代入
・探索用のqueに追加しておく．追加しておくことでまたそのノードとつながってるところを調べることができる
・最後は出力．全てのノードの最短距離を出力
"""

Python: from collections import deque

n = int(input())
g = [None] * n
visited = [0] * n
dist = [-1] * n
Q = deque()

while n:
    l = list(map(int, input().split()))
    g[l[0]-1] = [i-1 for i in l[2:]]
    n -= 1

Q.append((0, 0)) 
visited[0] = 1

while Q:
    i, d = Q.popleft()         
    dist[i] = d
    for c in g[i]:
        if not visited[c]:
            visited[c] = 1
            Q.append((c, d+1))

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

Python: from collections import deque
if __name__ == "__main__":
    n = int(input())
    graph = []
    for _ in range(n):
        v, k, *tmp = map(int, input().split())
        for j in range(len(tmp)):
            tmp[j] -= 1
        graph.append(tmp)
    visited = [False] * n
    qu = deque()
    qu.appendleft((0, 0))
    ans = [-1] * n
    visited[0] = True

    while qu:
        now, dis = qu.pop()
        ans[now] = dis

        for nei in graph[now]:
            if not visited[nei]:
                visited[nei] = True
                qu.appendleft((nei, dis + 1))
    for i in range(n):
        print(i+1,ans[i])

Python: from collections import deque

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

graph = [[] for _ in range(n+1)]
for u, k, *v in li:
    for i in v:
        graph[u].append(i)

ans = [-1] * (n+1)

ans[1] = 0
stack = deque([1])
while stack:
    num = stack.popleft()

    for s in graph[num]:
        if ans[s] == -1:
            stack.append(s)
            ans[s] = ans[num] + 1
            
for i, v in enumerate(ans[1:]):
    print(i+1, v)

Python: # -*- coding: utf-8 -*-
from collections import deque


if __name__ == '__main__':

    n = int(input())
    M = [[0 for i in range(n)] for j in range(n)]
    for _ in range(n):
        l = list(map(int, input().split(" ")))
        u = l[0]
        k = l[1]
        if k != 0:
            for v in l[2:]:
                M[u - 1][v - 1] = 1

    color = [0] * n
    d = [-1] * n
    Q = deque()

    def bfs(s):  # breadth-first search
        color[s] = 1
        d[s] = 0
        Q.append(s)

        while len(Q) != 0:
            u = Q.popleft()
            for v in range(n):
                if M[u][v] == 1 and color[v] == 0:
                    color[v] = 1
                    d[v] = d[u] + 1
                    Q.append(v)
            color[u] = 2

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

Python: import sys
input = lambda: sys.stdin.readline().rstrip() 
from collections import deque

def resolve():
    n = int(input())
    ukv = [list(map(int, input().split())) for _ in range(n)]

    dist = [-1]*n
    que = deque()

    que.append(0)
    dist[0] = 0
    while len(que)>0:
        v = que.popleft()
        for i in ukv[v][2:]:
            if dist[i-1]==-1:
                que.append(i-1)
                dist[i-1] = dist[v]+1

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

if __name__ == '__main__':
    resolve()

Python: #!/usr/bin/env python3
import sys
input = lambda: sys.stdin.readline()[:-1]
sys.setrecursionlimit(10**8)
from collections import deque

n=int(input())
G=[0]*n
memo=[0]*n
dis=[0]*n
dis[0]=1
que=deque()
que.append((0,1))

for i in range(n):
    inp=tuple(map(int,input().split()))
    G[inp[0]-1]=inp[2:]

while que:
    vertex,d=que.popleft()
    for v in G[vertex]:
        if not dis[v-1]:
            dis[v-1]=d+1
            que.append((v-1,d+1))
        

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

Python: def MAIN():
    n = int(input())
    li = [[] for _ in range(n + 1)]
    ans = [[i, 0] for i in range(n + 1)]
    for _ in range(n):
        u, k, *v = map(int, input().split())
        li[u] = v
    dp = [1]
    while dp:
        u = dp.pop()
        for v in li[u]:
            if ans[v][1] == 0:
                ans[v][1] = ans[u][1] + 1
                dp.append(v)
    for d in ans[1:]:
        print(*d)
MAIN()

Python: from collections import deque

class Vertex:
    _id = -1
    _children = []
    _depth = -1

    def __init__(self, i, c):
        self._id = i
        self._children = c

    def getId(self):
        return self._id

    def getChildren(self):
        return self._children

    def getDepth(self):
        return self._depth

    def setDepth(self, d):
        self._depth = d

    def print(self):
        print("{} {}".format(self._id, self._depth))


n = int(input())
graph = [0 for i in range(n)]
queue = deque([])

# 頂点登録
for i in range(n):
    u = list(map(int, input().split(' ')))
    adj = []
    if u[1] > 0:
        adj = u[2:u[1]+2]
    graph[u[0]-1] = Vertex(u[0], adj)

# BFS
graph[0].setDepth(0)
queue.append(graph[0])
while queue:
    v = queue.popleft()
    for u_id in v.getChildren():
        u = graph[u_id-1]
        if u.getDepth() == -1:
            u.setDepth(v.getDepth()+1)
            queue.append(u)

# 回答を出力
for v in graph:
    v.print()

Python: n = int(input())

m = [[0 for _ in range(n+1)] for _ in range(n+1)]
mm = [[] for _ in range(n+1)]

for _ in range(n):
	tmp = [int(x) for x in input().split()]
	u,k,l = tmp[0],tmp[1],tmp[2:]
	mm[u] += tmp[2:]
	for x in l:
		m[u][x] = 1
		
dp = [float('inf') for _ in range(n+1)]
dp[1] = 0
queue = [1]

'''
while queue:
	t = queue.pop(0)
	for i,x in enumerate(m[t]):
		if x == 1:
			if dp[i] > dp[t] + 1:
				dp[i] = dp[t] + 1
				queue.append(i)
			else:
				pass
		else:
			pass
'''

while queue:
	t = queue.pop(0)
	for x in mm[t]:
		if dp[x] > dp[t] + 1:
			dp[x] = dp[t] + 1
			queue.append(x)
			
for i,x in enumerate(dp):
	if i == 0:
		pass
	else:
		if x == float('inf'):
			print(i, -1)
		else:
			print(i, x)