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: #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	breadth_first_search
# CreatedDate:  2020-04-14 23:40:14 +0900
# LastModified: 2020-04-15 00:14:09 +0900
#


import os
import sys
from collections import deque

def bfs(matrix,n):
    s=0
    color=[0]*n
    color[s]=1
    Q=deque()
    Q.append(s)
    distance = [-1]*n
    distance[0]=0
    while Q:
        u = Q.popleft()
        for v in matrix[u]:
            if color[v]==0:
#                print("{}->{}".format(u,v))
                distance[v]=distance[u]+1
                color[v]=1
                Q.append(v)
        color[u]=2
    
    return distance

def main():
    n=int(input())
    matrix = [[] for _ in range(n)]
    for i in range(n):
        lined = map(int,input().split())
#        print(lined)
        for j,pon in enumerate(lined):
            if j>=2:
                matrix[i].append(pon-1)
#    print(matrix)
    distance = bfs(matrix,n)
    for i,di in enumerate(distance):
        print("{} {}".format(i+1,di))

if __name__ == "__main__":
    main()

Python: n = int(input())
a = [101] * n
a[0] = 0
for i in range(n):
    t = list(map(int, input().split()))
    del t[1]
    if len(t) >= 2:
        for j in range(1, len(t)):
            a[t[j] - 1] = min(a[t[j] - 1], a[t[0] - 1] + 1)
for i in range(n):
    if a[i] == 101:
        print("{} {}".format(i + 1, -1))
    else:
        print("{} {}".format(i + 1, a[i]))

Python: from collections import deque

n = int(input())
graph = [[] for _ in range(n)]
for i in range(n):
    graph[i] += list(map(lambda x: x - 1, list(map(int, input().split()))[2:]))

visited = [-1] * n
que = deque()
# 頂点0を入れておく
que.append(0)
visited[0] = 0
cnt = 0

while que:
    v = que.popleft()
    for nv in graph[v]:
        if not visited[nv] == -1:
            continue
        visited[nv] = visited[v] + 1
        que.append(nv)

for v, d in enumerate(visited, 1):
    print(v, d)

Python: from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def bfs(graph, initial):
    n = len(graph) - 1
    dist = [-1] * (n + 1)
    q = deque([initial])
    visited = [False] * (n + 1)
    visited[initial] = True
    dist[initial] = 0

    while len(q) != 0:
        edge = q.popleft()
        nxt = graph[edge]

        for i, e in enumerate(nxt):
            if visited[e] is False:
                q.append(e)
                dist[e] = dist[edge] + 1
                visited[e] = True

    return dist


def main():
    N = I()
    graph = [[] for i in range(N+1)]

    for i in range(N):
        a = LI()
        edge = a[0]
        if a[1] == 0:
            continue
        for e in a[2:]:
            graph[edge].append(e)
            # graph[e].append(edge)

    # print(graph)
    ret = bfs(graph, 1)
    for i in range(1, N+1):
        print(i, ret[i])


if __name__ == '__main__':
    main()

Python: import math
import copy
import sys
import fractions
# import numpy as np
# import statistics
import decimal
import heapq
import collections
import itertools
import bisect

# from operator import mul

sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputIntList():
    outputDataList = []
    inputData = input().split()
    outputDataList = [int(n) for n in inputData]

    return outputDataList


def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]

d = [-1] * n

for a in adj:
    for i in range(len(a)):
        a[i] -= 1

s = 0
q = collections.deque([])
d[s] = 0
q.append(s)
while len(q):
    u = q.popleft()
    v = adj[u]
    for vi in v:
        if d[vi] == -1:
            d[vi] = d[u] + 1
            q.append(vi)
        elif d[vi] > d[u] + 1:
            d[vi] = d[u] + 1
            q.append(vi)

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