Go: package main

import (
	"fmt"
	"os"
	"bufio"
	"strconv"
	"container/list"
)

const MaxNode int = 100

var d []int
var A [][]int
var N int
var l *list.List

func bfs(u int) {
	d[u] = 0
	l.PushBack(u)
	for ;l.Len() != 0; {
		u = l.Front().Value.(int)
		l.Remove(l.Front())
		for v:=0; v<N; v++ {
			if A[u][v] == 0 {
				continue
			}
			if d[v] != -1 {
				continue
			}
			d[v] = d[u] + 1
			l.PushBack(v)
		}
	}
}


func nextInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}

func print() {
	for i:=0; i<N; i++ {
		fmt.Printf("%d %d\n", i+1, d[i])
	}
}

func initVariable() {
	d = make([]int, MaxNode)
	A = make([][]int, MaxNode)
	l = list.New()
	for i:=0; i<MaxNode; i++ {
		A[i] = make([]int, MaxNode)
		d[i] = -1
	}
}


func main() {
	initVariable()
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	N = nextInt(scanner)
	for i:=0; i<N; i++ {
		idx := nextInt(scanner)
		cnt := nextInt(scanner)
		for j:=0; j<cnt; j++ {
			node := nextInt(scanner)
			A[idx-1][node-1] = 1 
		}
	}
	bfs(0)
	print()
}

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

Python: from collections import deque
n = int(input())
data = [None]*n
for _ in range(n):
    a,*b = map(int,input().split())
    a -= 1
    data[a] = [i-1 for i in b[1:]]
d = [-1]*n
dq = deque([(0,0)])
while dq:
    p,q = dq.popleft()
    if d[p] == -1:
        d[p] = q
        for i in data[p]:
            dq.append((i,q+1))
for i,j in enumerate(d):
    print(i+1,j)

Python: N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*N
while q:
 u=q.pop(0)
 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: N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*N
while q:
 u=q.pop(0)
 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: n=int(input())
dic=[[] for i in range(n)]
for i in range(n):
    a=list(map(int,input().split()))
    a=a[2:]
    dic[i]=list(map(lambda x:x-1,a))

from collections import deque
d=deque()
d.append(0) #始点
completed=[False]*n
distance=[999]*n
distance[0]=0
while d:
    now=d.popleft()
    completed[now]=True
    for x in dic[now]: #次の頂点探し
        if completed[x]==False: #その頂点に進んでもよいか
            distance[x]=min(distance[now]+1,distance[x])  #処理
            d.append(x)
for i in range(n):
    if distance[i]==999:
        distance[i]=-1
    print(i+1,distance[i])

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 = [-1] * n
isDiscovered = [False] * n

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

d_ = 0
isDiscovered [0] = True
d[0] = 0
bfs(0)

flag = True
while flag:
    flag = False
    for i in range(n):
        if d[i] is d_ :
            flag = True
            bfs(i)
    d_ += 1

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

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
4
1 2 2 4
2 1 4
3 0
4 1 3

output:
1 0
2 1
3 2
4 1
"""

import sys
from collections import deque

UNVISITED, VISITED_IN_QUEUE, POPPED_OUT = 0, 1, 2


def graph_bfs(v_init):
    queue = deque()
    visited[v_init] = VISITED_IN_QUEUE
    distance[v_init] = 0
    queue.appendleft(v_init)

    while queue:
        current = queue.popleft()
        for adj in adj_table[current]:
            if visited[adj] is UNVISITED:
                visited[adj] = VISITED_IN_QUEUE
                distance[adj] = distance[current] + 1
                queue.append(adj)
        visited[current] = POPPED_OUT
    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    v_num = int(_input[0])
    vertices = map(lambda x: x.split(), _input[1:])

    visited = [UNVISITED] * (v_num + 1)
    distance = [-1] * (v_num + 1)

    adj_table = tuple([] for _ in range(v_num + 1))
    for v_info in vertices:
        v_index, adj_num, *adj_list = map(int, v_info)
        # assert len(adj_list) == adj_num
        adj_table[v_index].extend(adj_list)

    graph_bfs(v_init=1)
    for index, v in enumerate(distance[1:], 1):
        print(index, v)

Python: 
def bfs(s):  # たぶんstartのs
    global n, M, color, d, q

    q.append(s)
    d[s] = 0

    while len(q) != 0:
        u = q.pop(0)

        for v in range(n):
            if M[u][v] != 1:
                continue

            if color[v] == 'WHITE':
                q.append(v)
                color[v] = 'GRAY'
                d[v] = d[u] + 1

        color[u] = 'BLACK'


n = int(input())

M = [[0 for i in range(n)] for j in range(n)]
color = ['WHITE'] * n  # 各頂点の色を記録。ホワイト（未探索）、グレイ（探索中）、ブラック（探索ずみ）
d = [-1] * n  # 始点0からvまでの距離
q = []

for i in range(n):
    _ = list(map(int, input().split()))
    u = _[0] - 1  # 0オリジンに変換

    degree = _[1]
    for j in range(degree):
        v = _[j+2] - 1  # 0オリジンに変換
        M[u][v] = 1

# for row in M:
#     print(' '.join(map(str, row)))

bfs(0)

for i in range(n):
    print('{} {}'.format(i+1, d[i]))

Python: N= int(input());E = [input().split()[2:] for _ in range(N)]
frag, T, L,Q = [0]*N, [0]*N, [0]*N, [0]
a,frag[0] = 100, 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[0];func(top);del Q[0]
for i in range(n):
    if L[i] == 0:
        L[i] == -1

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