Go: package main

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

type vertexId int

type vertex struct {
	id vertexId
	visitedAt int
	adjs []vertexId
}

func createVertex(id int, adjsInt []int) vertex {
	adjs := make([]vertexId, len(adjsInt))
	for i := 0; i < len(adjs); i++ {
		adjs[i] = vertexId(adjsInt[i])
	}
	return vertex{
		id: vertexId(id),
		visitedAt: -1,
		adjs: adjs,
	}
}

func (v *vertex) isVisited() bool {
	return v.visitedAt >= 0
}

func bfs(id vertexId, vqueue []vertexId, vertices []vertex) {
	vertex := &vertices[id-1]
	for _, vid := range vertex.adjs {
		if !vertices[vid-1].isVisited() {
			(&vertices[vid-1]).visitedAt = vertex.visitedAt+1
			vqueue = append(vqueue, vid)
		}
	}
	if len(vqueue) > 0 {
		nextId := vqueue[0]
		nextVqueue := vqueue[1:]
		bfs(nextId, nextVqueue, vertices)
	}
}

func solveBfs(vertices []vertex) {
	vertex := &vertices[0]
	vertex.visitedAt = 0
	vqueue := make([]vertexId, 0)
	bfs(vertex.id, vqueue, vertices)
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	vertices := make([]vertex, n)
	for i := 0; i < n; i++ {
		id, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		adjN, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		adjs := make([]int, adjN)
		for j := 0; j < adjN; j++ {
			adjId, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			adjs[j] = adjId
		}
		vertices[i] = createVertex(id, adjs)
	}

	solveBfs(vertices)

	for i := 0; i < n; i++ {
		fmt.Printf("%d %d\n", vertices[i].id, vertices[i].visitedAt)
	}
}

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextInt(sc *bufio.Scanner) (int, error) {
	return strconv.Atoi(nextText(sc))
}

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

Python: n = int(raw_input())
 
G = [0 for i in range(n)] 
a = [[0 for i in range(n)] for j in range(n)]
dis = [-1 for i in range(n)]
dis[0] = 0

for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        a[G[0]-1][G[2+j]-1] = 1
 
def bfs_visit(s):
    for k in range(n):
      if a[s][k] == 1:
       if dis[k] == -1:
         dis[k] = dis[s] + 1
         bfs_visit(k)

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

Python: # -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    #print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] <= 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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