Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

func stringifyArray(arr []int) string {
	return strings.TrimRight(fmt.Sprintf("%+v", arr)[1:], "]")
}

var infty = 1000000000

type nodeKey int

type DirectedGraphNode struct {
	key       nodeKey
	adjacents []*DirectedGraphNode
	visited   bool
	d         int
	parent    *DirectedGraphNode
}

type DirectedGraph struct {
	nodes []DirectedGraphNode
}

func (g *DirectedGraph) setAdjacency(l, r nodeKey) {
	g.nodes[l].adjacents = append(g.nodes[l].adjacents, &g.nodes[r])
}

func newDirectedGraph(nNodes int) *DirectedGraph {
	graph := DirectedGraph{}
	graph.nodes = make([]DirectedGraphNode, nNodes)
	for iNodes := 0; iNodes < nNodes; iNodes++ {
		graph.nodes[iNodes].key = nodeKey(iNodes)

		graph.nodes[iNodes].visited = false
		graph.nodes[iNodes].d = infty
		graph.nodes[iNodes].parent = nil
	}
	return &graph
}

type QueueEntry struct {
	node *DirectedGraphNode
	next *QueueEntry
}

type Queue struct {
	head, tail *QueueEntry
}

func (q *Queue) enqueue(node *DirectedGraphNode) {
	entry := QueueEntry{}
	entry.node = node

	if q.tail == nil {
		q.head = &entry
		q.tail = &entry
		return
	}

	q.tail.next = &entry
	q.tail = q.tail.next
}

func (q *Queue) dequeue() *QueueEntry {
	if q.head == nil {
		return nil
	}
	poped := q.head
	q.head = q.head.next
	if q.head == nil {
		q.tail = nil
	}
	return poped
}

func (q *Queue) isEmpty() bool {
	return q.head == nil
}

func fillDistancesByBreadthFirstSearch(g *DirectedGraph, startNode *DirectedGraphNode) {
	startNode.visited = true
	startNode.d = 0

	queue := Queue{}
	queue.enqueue(startNode)
	for !queue.isEmpty() {
		u := queue.dequeue().node
		for _, adjacent := range u.adjacents {
			if !adjacent.visited {
				adjacent.visited = true
				adjacent.d = u.d + 1
				adjacent.parent = u
				queue.enqueue(adjacent)
			}
		}
		u.visited = true
	}
}

func main() {
	scanner.Split(bufio.ScanWords)

	nNodes := nextInt()
	g := newDirectedGraph(nNodes + 1)

	for iNode := 0; iNode < nNodes; iNode++ {
		nodeKeyLeft := nodeKey(nextInt())
		nAdj := nextInt()
		for iAdj := 0; iAdj < nAdj; iAdj++ {
			nodeKeyRight := nodeKey(nextInt())
			g.setAdjacency(nodeKeyLeft, nodeKeyRight)
		}
	}

	// fmt.Println(g)
	fillDistancesByBreadthFirstSearch(g, &g.nodes[1])
	// fmt.Println(g)

	for iNode := 1; iNode <= nNodes; iNode++ {
		node := g.nodes[iNode]
		distance := node.d
		if distance == infty {
			distance = -1
		}
		fmt.Println(node.key, distance)
	}
}

Python: from collections import deque

N = int(input())
E = [None] * (N+1)
for _ in range(N):
    u, k, *vs = list(map(int, input().split()))
    E[u] = vs

d = [-1] * (N+1)
d[1] = 0
q = deque([(1, 0)])
while q:
    v, c = q.popleft()
    for u in E[v]:
        if d[u] < 0:
            d[u] = c+1
            q.append((u, c+1))

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

Python: from collections import deque
from enum import Enum, auto

class Color(Enum):
    WHITE = auto()
    GRAY = auto()
    BLACK = auto()

n = int(input())
d = [0 for i in range(n)]
f = [0 for i in range(n)]

colors = [] # 頂点の訪問状態
A = [[0 for j in range(n)] for i in range(n)] # 隣接行列
queue = deque([])

# 隣接行列の初期化
for i in range(n):
    arr = list(map(int, input().split(' ')))
    u, k, v = arr[0], arr[1], arr[2:]
    for j in range(k):
        A[u-1][v[j]-1] = 1

def bfs_init():
    global colors
    colors = [Color.WHITE for i in range(n)]
    d[0] = 0
    bfs(0)

def bfs(u):
    global queue
    colors[u] = Color.GRAY

    for v in range(n):
        if A[u][v] == 1 and colors[v] == Color.WHITE and v not in queue:
            d[v] = d[u] + 1
            queue.append(v)

    while len(queue) > 0:
        v = queue.pop()
        bfs(v)

bfs_init()

for u in range(n):
    if colors[u] == Color.WHITE:
        d[u] = -1

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

Python: import queue
n = int(input())

g = {}
for i in range(n):
    x = list(map(int, input().split()))
    g[x[0]] = [x[2:], 'w', x[0], None]

q = queue.Queue()
node = g[1]
node[-1] = 0
node[1] = 'g'
q.put(node)

while not q.empty():
    node  = q.get()
    d = node[-1] + 1
    for i in node[0]:
        ch = g[i]
        if ch[1] == 'w':
            ch[-1] = d
            ch[1] = 'g'
            q.put(ch)

for i in range(n):
    node = g[i+1]
    if node[-1] == None:
        d = -1
    else:
        d = node[-1]
    print("{} {}".format(i+1, d))

Python: #!/usr/bin/env python3

from collections import deque

n = int(input())

edges = [[] for _ in range(n)]
for _ in range(n):
    line = list(map(int, input().split()))
    u = line[0] - 1
    if len(line) != 2:
        v_list = line[1:]
        for v in v_list:
            edges[u].append(v - 1)
# print(n, edges)

dist = [-1 for _ in range(n)]
que = deque()


def dfs(que, dist):
    while len(que) > 0:
        v = que.popleft()

        for v_adj in edges[v]:
            if dist[v_adj] == -1:
                dist[v_adj] = dist[v] + 1
                que.append(v_adj)


dist[0] = 0
que.appendleft(0)
dfs(que, dist)

for i in range(n):
    print(f"{i + 1} {dist[i]}")

Python: from collections import defaultdict
v_num = int(input())
connect = defaultdict(list)
for v in range(v_num):
    inp = [int(n) - 1 for n in input().split(" ")]
    connect[inp[0]].extend(inp[2:])
answer = [[m + 1, -1] for m in range(v_num)]
queue = [0]
visited = [0 for n in range(v_num)]
visited[0] = 1
time = 0
while queue:
    new_queue = []
    for q in queue:
        answer[q][1] = time
        for c in connect[q]:
            if not visited[c]:
                visited[c] = 1
                new_queue.append(c)
    queue = new_queue
    time += 1
for v in range(v_num):
    print(*answer[v])

Python: from collections import deque

WHITE = 0
GRAY = 1
BLACK = 2

n = int(input())

M = [[0] * n for i in range(n)]

d = [-1] * (n)
color = [WHITE] * (n)


time = 0

def dfs_visit(u):
    global time
    time += 1
    color[u] = GRAY
    d[u] = time
    for v in range(n):
        if M[u][v] == 0:
            continue
        if color[v] == WHITE:
            dfs_visit(v)
    color[u] = BLACK
    time += 1

def bfs(s):
    queue = deque([])
    queue.append(s)
    d[s] = 0
    while len(queue) > 0:
        u = queue.popleft()
        for v in range(n):
            if M[u][v] == 0:
                continue
            if d[v] != -1:
                continue
            d[v] = d[u] + 1
            queue.append(v)

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


if __name__ == "__main__":
    for i in range(n):
        arr = list(map(int, input().split()))
        for v in (arr[2:]):
            M[arr[0]-1][v-1] = 1

    bfs(0)

Python: n=int(input())
G=[[0,[],0,-1]]
for i in range(n):
    v=[int(j) for j in input().split(" ")]
    u=v.pop(0)
    k=v.pop(0)
    G.append([k,v,0,-1])





distance=0
dis_list=[1]
G[1][3]=0
G[1][2]=1
while len(dis_list)!=0:
    distance+=1
    for i in dis_list:
        dis_list_cash=[]
        k=G[i][0]
        v=G[i][1]
        for j in range(k):
            if G[v[j]][2]==0:
                G[v[j]][2]=1
                G[v[j]][3]=distance
                dis_list_cash.append(v[j])
    dis_list=dis_list_cash


for i in range(1,n+1):
    print(str(i)+" "+str(G[i][3]))