Go: package main

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

func main() {
	scn := bufio.NewScanner(os.Stdin)
	scn.Split(bufio.ScanWords)
	nextInt := func() int { scn.Scan(); r, _ := strconv.Atoi(scn.Text()); return r }
	w := bufio.NewWriter(os.Stdout)

	n := nextInt()
	vecs := make([][]int, n)
	for i := 0; i < n; i++ {
		u := nextInt()
		k := nextInt()
		for j := 0; j < k; j++ {
			vecs[u-1] = append(vecs[u-1], nextInt()-1)
		}
	}

	ds := make([]int, 0, n)
	for i := 0; i < n; i++ {
		ds = append(ds, -1)
	}

	q := make([]int, 0, n)
	q = append(q, 0)
	ds[0] = 0

	for len(q) > 0 {
		i := pop(&q)
		for _, v := range vecs[i] {
			if ds[v] == -1 {
				ds[v] = ds[i]+1
				q = append(q, v)
			}
		}
	}

	for i, d := range ds {
		fmt.Fprintln(w, i+1, d)
	}

	w.Flush()
}

func pop(q *[]int) int {
	v := (*q)[0]
	*q = (*q)[1:]
	return v
}

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

N = int(input())
adj = [[0]*N for _ in range(N)]
unsearched = set(range(1, N))
result = {n:-1 for n in range(N)}

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

que = deque([[0, 0]]) # edge distance


while len(que):
    q = que.pop()
    result[q[0]] = q[1]
    next_ = [[i, q[1] + 1] for i, a in enumerate(adj[q[0]]) if (a==1) & (i in unsearched)]
    unsearched = unsearched.difference([i[0] for i in next_])
    que.extendleft(next_)

for n in range(N):
    print("{} {}".format(n+1, result[n]))

Python: N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*~-N
while q:
 u=q.pop()
 for v in M[u]:
  v=int(v)-1
  if d[v]<0:d[v]=d[u]+1;q+=[v]
for i in range(N):print(i+1,d[i])

Python: # Graph I - Breadth First Search
from collections import deque
def bfs(A,d):
    dq = deque()
    dq.append(0)
    d[0] = 0
    while len(dq):
        v = dq.pop()
        for i in range(len(A[v])-1,-1,-1):
            f = A[v][i]
            if f == 1 and d[i] == -1:
                d[i] = d[v] + 1
                dq.appendleft(i)

n = int(input())
A = []
for _ in range(n):
    ss = list(map(int, input().split()))
    u = ss[0] - 1
    row = [0 for _ in range(n)]
    for i in range(ss[1]):
        idx = 2 + i
        row[ss[idx]-1] = 1
    A.append(row)

d = [-1 for _ in range(n)]
bfs(A,d)

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

Python: from collections import deque
n = int(input())
grap = [[]]
for i in range(n):
    u,k,*v = map(int,input().split())
    grap.append(v)

dis = [-1]*(n+1)
dis[0] = 0
dis[1] = 0

d = deque()
d.append(1)
while d:
    v = d.popleft()
    for i in grap[v]:
        if dis[i] != -1:
            continue
        dis[i] = dis[v] + 1
        d.append(i)

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

Python: import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n = ni()
g = []
for i in range(n):
    t = na()
    u = t[0] - 1
    k = t[1]
    v = [x-1 for x in t[2:]]
    g.append(v)
dist = [-1] * n
que = deque()
dist[0] = 0
que.append(0)
while que:
    #print(que)
    v = que.popleft()
    for nv in g[v]:
        if dist[nv] != -1: continue
        dist[nv] = dist[v] + 1
        que.append(nv)

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

Python: import queue

def main():
    n = int(input())
    rows = []
    for i in range(n):
        rows.append([int(x) for x in input().split()])

    vum = {}
    for row in rows:
        u,k = row[0],row[1]
        ul = []
        if k > 0:
            for j in row[2:]:
                ul.append(j)
        vum.update({u:ul})
    # print(vum)

    ### bfs ###
    q = queue.Queue()
    D = [-1]*n # 最短距離
    s = 1 # 始点
    step = 0
    D[s-1] = step
    while True:
        # print('s',str(s))
        step = D[s-1] + 1
        for v in vum[s]:
            # print('v',str(v))
            if D[v-1] < 0:
                # print('append v',str(v),str(step))
                q.put(v)
                D[v-1] = step
        if q.empty():
            break
        # print(list(q.queue),V)
        s = q.get()

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

if __name__ == '__main__':
    main()

Python: import queue,sys
N=int(input())
M=[list(map(int,e.split()[2:]))for e in sys.stdin]
q=queue.Queue();q.put(0)
d=[-1]*N;d[0]=0
while q.qsize()>0:
 u=q.get()
 for v in M[u]:
  v-=1
  if d[v]<0:d[v]=d[u]+1;q.put(v)
for i in range(N):print(i+1,d[i])

Python: from collections import deque

n = int(input())
m = [[0 for j in range(n)] for i in range(n)]
color = [0 for i in range(n)]
q = deque()
dist = [-1 for i in range(n)]


def bfs(s):
    color[s], dist[s] = 1, 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], dist[v] = 1, dist[u] + 1
                q.append(v)

        color[u] = 2


def main():
    for i in range(n):
        data = list(map(int, input().split()))
        for j in range(2, len(data)):
            m[data[0]-1][data[j]-1] = 1

    bfs(0)

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


if __name__ == '__main__':
    main()

Python: from collections import deque

N = int(input())
inf = 10 ** 6
graph = [[] for i in range(N)]
distance = [inf for i in range(N)]

for i in range(N):
  a = list(map(int,input().split()))
  a = list(map(lambda x: x - 1,a))
  k,n = a[0],a[1]
  if n >= 0:
    graph[k] = a[2:]
    

def bfs(path,root,dist):
  dist[root] = 0
  queue = deque([root])
  while queue:
    cur = queue.popleft()
    for chi in path[cur]:
      if dist[chi] == inf:
        queue.append(chi)
      dist[chi] = min(dist[cur] + 1,dist[chi])

bfs(graph,0,distance)
distance = [-1 if i == inf else i for i in distance]

for i,j in enumerate(distance):
  print(i + 1,j)

Python: N= int(input())
E = [input().split()[2:] for _ in range(N)]
frag, T, L,Q = [0]*N, [0]*N,[0] + [-1]*N, [0]
frag[0] = 1
def func(ide):
    for i in E[ide]:
        i = int(i) - 1
        if frag[i] != 1:frag[i] = 1;L[i] = L[ide] +1 ;Q.append(i) 
        else:return

while Q:top = Q.pop();func(top)

for i in range(N):print(i + 1 ,int(L[i]))

Python: #coding:utf-8
n = int(input())
Q = [1]
M = [[False for i in range(n)] for j in range(n)]
dataList = []
for i in range(n):
    data = list(map(int,input().split()))
    dataList.append(data)
    for j in range(data[1]):
        v = data[j+2] - 1
        M[i][v] = True
color = ["white" for i in range(n)]
d = [0 for i in range(n)]

while Q != []:
    u = Q.pop() - 1
    color[u] = "gray"
    data = dataList[u]
    for i in range(data[1]):
        v = data[i+2] - 1
        if M[u][v] == True and color[v] == "white":
            d[v] = d[u] + 1
            Q.append(v+1)
    color[u] = "black"

print(" ".join([str(num) for num in d]))

Python: n = int(input())
a = [[] for i in range(n)]

for i in range(n):
    v = list(map(int, input().split()))
    u = v[0] - 1
    for j in v[2:]:
        a[u].append(j-1)

d = [0] * n
isDiscovered = [False] * n

def bfs(x):
    global time_stamp
    time_stamp += 1
    for i in a[x]:
        if not isDiscovered[i]:
            isDiscovered [i] = True
            d[i] = d[x] + 1

bfs(0)
d_ = 1
isDiscovered [0] = True
while not(isDiscovered == [True] * n):
    for i in range(n):
        if d[i] is d_ :
            bfs(i)
    d_ += 1

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