Go: package main

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

//util
var sc = bufio.NewScanner(os.Stdin)

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func printList(list []int) {
	n := len(list)
	buf := bufio.NewWriter(os.Stdout)
	for _, v := range list[0 : n-1] {
		buf.Write([]byte(fmt.Sprintf("%d ", v)))
	}
	buf.Write([]byte(fmt.Sprintf("%d\n", list[n-1])))
	buf.Flush()
}

func max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

//solve
const INFTY = (1 << 21)
const MAX = 100
const WHITE = 0
const GRAY = 1
const BLACK = 2

var time, n int

//隣接行列
var M [MAX][MAX]int

//d[i]: 頂点1から頂点iまでの距離
var color, d [MAX]int

func bfs(s int) {
	var q []int
	q = append(q, s)
	for i := 0; i < n; i++ {
		d[i] = INFTY
	}
	//sは開始点なので、0をいれる
	d[s] = 0

	//キューが空になるまで、以下を繰り返す
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		for v := 0; v < n; v++ {
			if M[u][v] == 0 {
				continue
			}
			if d[v] != INFTY {
				continue
			}
			d[v] = d[u] + 1
			q = append(q, v)
		}
	}

	for i := 0; i < n; i++ {
		fmt.Printf("%d ", i+1)
		if d[i] == INFTY {
			fmt.Printf("%d\n", -1)
		} else {
			fmt.Printf("%d\n", d[i])
		}
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n = nextInt()
	for i := 0; i < n; i++ {
		u, k := nextInt(), nextInt()
		M[u-1][u-1] = 0

		//fmt.Println(u, k)
		if k > 0 {
			for j := 0; j < k; j++ {

				v := nextInt()
				M[u-1][v-1] = 1

			}
		}

	}

	bfs(0)

}

Python: n = int(input())

adj = [None]
for i in range(n):
    adj_i = list(map(int, input().split()[2:]))
    adj.append(adj_i)

isSearched = [None] + [False] * n

distance = [None] + [-1] * n

import collections

def bfs(u):
    isSearched[u] = True
    distance[u] = 0
    edge = collections.deque()
    edge.append(u)
    while edge:
        c_e = edge.popleft()
        for n_e in adj[c_e]:
            if not isSearched[n_e]:
                isSearched[n_e] = True
                distance[n_e] = distance[c_e] + 1
                edge.append(n_e)


bfs(1)

for i, x in enumerate(distance[1:], start=1):
    print(i, x)

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()