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: import collections

def breadth_first_search(g,check,length):
    q = collections.deque()
    q.append(1)
    check[1] = 1
    length[1] = 0
    while len(q) != 0:
        v = q.popleft()
        for u in g[v]:
            if check[u] == 0:
                check[u] = 1
                length[u] = length[v]+1
                q.append(u)

    return length

def main():
    N = int(input())
    g = []
    g.append([])
    for i in range(N):
        tmp = input().split()
        tmp_ls = []
        for i in range(int(tmp[1])):
            tmp_ls.append(int(tmp[i+2]))
        g.append(tmp_ls)

    check = [0]*(N+1)
    length = [0]*(N+1)
    ans = breadth_first_search(g,check,length)
    for i in range(N):
        node_num = i+1
        if ans[node_num] == 0 and i != 0:
            ans[node_num] = -1
        print(node_num,ans[node_num])

main()

Python: from collections import deque

def main():
    n = int(input())
    V = [None]*(n+1)
    ans = [None]*(n+1)
    for i in range(1, n+1):
        _, _, *v = map(int, input().split())
        V[i] = v
    q = deque([1])
    ans[1] = 0
    while q:
        node = q.pop()
        d = ans[node]+1
        for v in V[node]:
            if ans[v] is None:
                ans[v] = d
                q.appendleft(v)
    print(1, 0)
    for i, distance in enumerate(ans[2:], 2):
        print(i, distance or -1)

if __name__ == "__main__":
    main()

Python: N= int(input())
E = [input().split()[2:] for _ in [0]*N]
Q = [0]
L = [0] + [-1]*N
def func(ide):
    for i in E[ide]:
        i = int(i) - 1
        if L[i] < 0 :L[i] = L[ide] +1 ; Q+= [i]


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

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

Python: from collections import deque
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
d=deque()
d.append(1)
check=[0]*n
check[0]=1
ans=[0]*n
kyori=[0]*n
while len(d)!=0:
  v=d.popleft()
  for i in l[v-1][2:]:
    if check[i-1]==0:
      check[i-1]=1
      ans[i-1]=(kyori[v-1]+1)
      kyori[i-1]=(kyori[v-1]+1)
      d.append(i)
for i in range(1,n):
  if ans[i]==0:
    ans[i]=-1
for i in range(n):
    print(i+1,ans[i])

Python: # coding: utf-8

from queue import Queue

N = int(input())
graph = [None]
for _ in range(N):
    graph.append(list(map(int, input().split(" ")))[1:])

class BFSSolver:

    def __init__(self, graph):
        self.graph = graph
        self.queue = Queue()
        self.queue.put(1)
        self.before_id = 1
        self.already_searched = [1]
        self.res = [0]
        for _ in range(N):
            self.res.append(-1)
        self.res[1] = 0
        self.turn = 0

    def next_turn(self):
        now_id = self.queue.get()
        before_id = now_id
        neighbors = self.graph[now_id][1:]
        for i in neighbors:
            if i not in self.already_searched:
                self.turn = self.res[before_id] + 1
                self.already_searched.append(i)
                self.res[i] = self.turn
                self.queue.put(i)

    def solve(self):
        while not self.queue.empty():
            self.next_turn()

        for id, i in enumerate(self.res[1:]):
            print("{} {}".format(id+1, i))

s = BFSSolver(graph)
s.solve()

Python: #!/usr/bin/python3

def find(id, V, d, dist):
    i = id - 1
    dist[i] = d
    for v in V[i]:
        find(v, V, d + 1, dist)
    
n = int(input())
# [isFind, d, f]
A = [[False, 0, 0] for i in range(n)]
U = []
V = []
dist = [-1] * n
for i in range(n):
    l = list(map(int, input().split()))
    U.append(l[0])
    V.append(l[2:])

find(1, V, 0, dist)

for u in U:
    print(u, dist[u - 1])

Python: import collections

N = int(input())
UKV = [list(map(int,input().split())) for _ in range(N)]

dist = [-1]*N
que = collections.deque()

G = [[]]*N
for ukv in UKV:
    G[ukv[0]-1] = sorted(ukv[2:])

dist[0] = 0
que.append(1)

while len(que) != 0:
    v = que.popleft()
    for nv in G[v-1]:
        if dist[nv-1] != -1:
            continue
        dist[nv-1] = dist[v-1] + 1
        que.append(nv)

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

Python: # -*- coding: utf-8 -*-                                                                                                                                                                                                                               

def BFS(adj, start):
    n = len(adj)
    d = [n] * n
    flag = [0] * n
    Q = []

    Q.append(start)
    d[start] = 0

    while len(Q) != 0:
        u = Q.pop(0)
        v = [i for i, x in enumerate(adj[u]) if (x == 1) and (flag[i] == 0)] # v <= ??£??\???????????????????????¢?´¢??????????????????
        
        for i in v:
            Q.append(i)
            d[i] = min(d[u] + 1, d[i])
            flag[u] = 1
    
    for i in range(n):
        if d[i] == n:
            d[i] = -1

    return d

def main():
    n = int(input())
    adj = [[0 for i in range(n)] for j in range(n)]
    
    for i in range(n):
        tmp = list(map(int, input().split()))
        u = tmp[0]
        u = u -1
        k = tmp[1]
        v = tmp[2:]
        for j in range(k):
            adj[u][v[j]-1] = 1
    
    d = BFS(adj, 0)
    for i in range(n):
        print(i+1, d[i])


if __name__ == "__main__":
    main()