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: #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 = [-1 for i in range(n)]
d[0] = 0
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: #!/usr/bin/env python3

import sys
# SimpleQueue でOKなのだが AOJ の環境では Python3.7 が使えない
from queue import Queue


class BFS():
    INFTY = sys.maxsize

    def __init__(self, M, n, debug=False):
        self.M = M
        self.n = n
        # 距離で訪問状態(color)を管理する
        self.d = [self.INFTY] * n
        self.debug = debug

    def bfs(self, s):
        q = Queue()
        q.put(s)
        self.d[s] = 0
        self.debug_print(q)

        while not q.empty():
            u = q.get()
            for v in range(self.n):
                if self.M[u][v] == 0:
                    continue
                if self.d[v] != self.INFTY:
                    continue
                self.d[v] = self.d[u] + 1
                q.put(v)
                self.debug_print(q)

        for i in range(self.n):
            if self.d[i] == self.INFTY:
                d = -1
            else:
                d = self.d[i]
            print(f'{i+1} {d}')

    def debug_print(self, q):
        if not self.debug:
            return
        print('d: ', self.d)
        print('q: ', q.queue)
        print('-------------------------')


def main():
    n = int(input())
    M = [[0] * n for _ in range(n)]

    for i in range(n):
        line = input()
        inputs = [int(x) for x in line.split(' ')]
        u = inputs.pop(0)
        u -= 1                  # 0 オリジンへ変換
        _ = inputs.pop(0)       # k （使わない...）
        for v in inputs:
            v -= 1              # 0 オリジンへ変換
            M[u][v] = 1

    BFS(M, n).bfs(0)


if __name__ == '__main__':
    main()

Python: import collections
n=int(input())
l=[]
for i in range(n):
  l1=list(map(int,input().split()))
  l2=[]
  if l1[1]==0:
    l2=["0" for j in range(n)]
  else:
    for j in range(n):
      if j+1 in l1[2:]:
        l2.append("1")
      else:
        l2.append("0")
  l.append(l2)
D=[-1 for i in range(n)]
D[0]=0
q=collections.deque()
q.append(0)
while len(q)!=0:
  cur=q.popleft()
  for d in range(n):
    if l[cur][d]=="1" and D[d]==-1:
      D[d]=D[cur]+1
      q.append(d)
for i in range(n):
  print(i+1,D[i])

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: # -*- coding: utf-8 -*-
from collections import deque

N = int(input())
adj = [[0]*N for _ in range(N)]
unsearched = set(range(1, N))
result = {n:-1 for n in range(N)}

for n in range(N):
    inp = list(map(int, input().split()))
    for i in inp[2:]:
        adj[inp[0]-1][i-1] = 1

que = deque([[0, 0]]) # edge distance


while len(que):
    q = que.pop()
    result[q[0]] = q[1]
    next_ = [[i, q[1] + 1] for i, a in enumerate(adj[q[0]]) if (a==1) & (i in unsearched)]
    unsearched = unsearched.difference([i[0] for i in next_])
    que.extendleft(next_)

for n in range(N):
    print("{} {}".format(n+1, result[n]))

Python: N=int(input())
M=[input().split()[2:]for _ in[0]*N]
q=[0]
d=[0]+[-1]*~-N
while q:
 u=q.pop()
 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: # Graph I - Breadth First Search
from collections import deque
def bfs(A,d):
    dq = deque()
    dq.append(0)
    d[0] = 0
    while len(dq):
        v = dq.pop()
        for i in range(len(A[v])-1,-1,-1):
            f = A[v][i]
            if f == 1 and d[i] == -1:
                d[i] = d[v] + 1
                dq.appendleft(i)

n = int(input())
A = []
for _ in range(n):
    ss = list(map(int, input().split()))
    u = ss[0] - 1
    row = [0 for _ in range(n)]
    for i in range(ss[1]):
        idx = 2 + i
        row[ss[idx]-1] = 1
    A.append(row)

d = [-1 for _ in range(n)]
bfs(A,d)

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

Python: from collections import deque
n = int(input())
grap = [[]]
for i in range(n):
    u,k,*v = map(int,input().split())
    grap.append(v)

dis = [-1]*(n+1)
dis[0] = 0
dis[1] = 0

d = deque()
d.append(1)
while d:
    v = d.popleft()
    for i in grap[v]:
        if dis[i] != -1:
            continue
        dis[i] = dis[v] + 1
        d.append(i)

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