Go: package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	num, _ := strconv.Atoi(sc.Text())
	nodes := make(map[int]*node)

	for i := 0; i < num; i++ {
		sc.Scan()
		id, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		nodeNum, _ := strconv.Atoi(sc.Text())
		n := node{id, make([]int, 0), -1}
		for j := 0; j < nodeNum; j++ {
			sc.Scan()
			nid, _ := strconv.Atoi(sc.Text())
			n.nexts = append(n.nexts, nid)
		}
		nodes[id] = &n
	}
	nodes[1].depth = 0

	walk(1, 0, &nodes)
	for i := 1; i < len(nodes)+1; i++ {
		fmt.Printf("%v %v\n", (*nodes[i]).id, (*nodes[i]).depth)
	}
}

var time int
var record [100][100]bool
var q Queue

func walk(nid int, from int, nodes *map[int]*node) {
	q.Enqueue((*nodes)[nid])
	for !q.IsEmpty() {
		n := q.Dequeue().(*node)
		for _, v := range n.nexts {
			n2 := (*nodes)[v]
			if n2.depth != -1 {
				continue
			}
			n2.depth = n.depth + 1
			q.Enqueue((*nodes)[v])
		}
	}
}

type node struct {
	id    int
	nexts []int
	depth int
}

// Queue is Queue
type Queue struct {
	val []interface{}
}

// Enqueue value
func (queue *Queue) Enqueue(val interface{}) {
	queue.val = append(queue.val, val)
}

// Dequeue value
func (queue *Queue) Dequeue() interface{} {
	res := queue.val[0]
	queue.val = queue.val[1:len(queue.val)]
	return res
}

// IsEmpty return true when queue is empty
func (queue *Queue) IsEmpty() bool {
	return len(queue.val) == 0
}

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)