Go: package main

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

type AdjacentList struct {
	matrix [][]int
}

func NewEmptyAdjacentList(dim int) *AdjacentList {
	matrix := make([][]int, dim)
	for i := 0; i < dim; i++ {
		matrix[i] = make([]int, dim)
	}
	return &AdjacentList{matrix: matrix}
}

func (al *AdjacentList) set(node int, adjacent int) {
	al.matrix[node-1][adjacent-1] = 1
}

func (al *AdjacentList) findAdjacentsFor(node int) []int {
	adjacents := []int{}
	for i, v := range al.matrix[node-1] {
		if v == 1 {
			adjacents = append(adjacents, i+1)
		}
	}
	return adjacents
}

type DistanceList struct {
	list []int
}

func NewDistanceList(dim int) *DistanceList {
	list := make([]int, dim)
	for i := 0; i < dim; i++ {
		list[i] = -1
	}
	return &DistanceList{list: list}
}

func (dl *DistanceList) set(node int, distance int) {
	dl.list[node-1] = distance
}

func (dl *DistanceList) get(node int) int {
	return dl.list[node-1]
}

func (dl *DistanceList) isVisited(node int) bool {
	return dl.list[node-1] >= 0
}

type Position struct {
	node     int
	distance int
}

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

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

	al := NewEmptyAdjacentList(dim)

	for i := 1; i <= dim; i++ {
		node, err := nextInt(sc)
		if err != nil {
			panic(err)
		}

		adjacentNum, err := nextInt(sc)
		if err != nil {
			panic(err)
		}
		for j := 0; j < adjacentNum; j++ {
			adjacent, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			al.set(node, adjacent)
		}
	}

	dl := NewDistanceList(dim)

	bfs(al, dl)

	for i := 1; i <= dim; i++ {
		fmt.Printf("%d %d\n", i, dl.get(i))
	}
}

func bfs(al *AdjacentList, dl *DistanceList) {
	stack := []Position{Position{node: 1, distance: 0}}
	for len(stack) > 0 {
		currentPosition := stack[0]
		stack = stack[1:]
		if !dl.isVisited(currentPosition.node) {
			dl.set(currentPosition.node, currentPosition.distance)
		}
		for _, v := range al.findAdjacentsFor(currentPosition.node) {
			stack = append(stack, Position{node: v, distance: currentPosition.distance + 1})
		}
	}
}

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

Python: import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def bfs(n, adj):
    dis = [-1] * n
    visited = [False] * n
    nxt = deque([0])
    dis[0] = 0
    visited[0] = True

    while nxt:
        u = nxt.popleft()

        for v in adj[u]:
            if not visited[v]:
                dis[v] = dis[u] + 1
                visited[v] = True
                nxt.append(v)

    return dis

def solve():
    n = int(input())
    adj = [None] * n
    for i in range(n):
        u, k, *vs = [int(j) - 1 for j in input().split()]
        adj[u] = vs

    # debug(adj, locals())
    dis = bfs(n, adj)

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

    pass

if __name__ == '__main__':
    solve()

Python: n = int(input())
al = [list(map(lambda x: int(x) - 1, input().split()))[2:] for _ in range(n)]
queue = [0]
d = [-1] * n
d[0] = 0
while len(queue) > 0:
    u = queue.pop(0)
    for v in al[u]:
        if d[v] == -1:
            d[v] = d[u] + 1
            queue.append(v)
for i, x in enumerate(d):
    print('{} {}'.format(i + 1, x))

Python: from collections import deque

n = int(input())
g = [list(map(int, input().split()))[2:] for _ in range(n)]
que = deque([0])
dist = [-1] * n
dist[0] = 0  # 初期条件
while que:  # queが空なるまで
    u = que.popleft()  # queの左から順に取り出す
    for v in g[u]:
        v -= 1  # 0-indexedに変更
        if dist[v] == -1:  # 未探索の時
            dist[v] = dist[u] + 1  # 最短距離を記録
            que.append(v)  # queに追加
for i in range(n):
    print(i + 1, dist[i])

Python: # -*- coding: utf_8 -*-

level = True
def debug(v):
    if level:
        print(v)

NOT_FOUND = 0
ENQUEUED = 1
FOUND = 2

def bfs(graph, status, results):
    queue = []
    queue.append(1)
    while len(queue) != 0:
        node = queue.pop(0)
        status[node] = FOUND
        d = results[node]
        for edge in graph[node]:
            if status[edge] != NOT_FOUND:
                continue
            status[edge] = ENQUEUED
            queue.append(edge)
            results[edge] = d + 1

    return results

if __name__ == "__main__":
    n = int(input())
    status = [NOT_FOUND] * (n + 1)
    results = [0] * (n + 1)
    g = [[0]]

    for i in range(n):
        row = [int(x) for x in input().split()]
        row.pop(0)
        row.pop(0)
        g.append(row)

    bfs(g, status, results)
    results.pop(0)

    print(results)
    for idx, v in enumerate(results):
        print(idx + 1, v)

Python: n = int(input())

m = [[0 for _ in range(n+1)] for _ in range(n+1)]
mm = [[] for _ in range(n+1)]

for _ in range(n):
	tmp = [int(x) for x in input().split()]
	u,k,l = tmp[0],tmp[1],tmp[2:]
	mm[u] += tmp[2:]
	for x in l:
		m[u][x] = 1
		
dp = [float('inf') for _ in range(n+1)]
queue = [1]

while queue:
	t = queue.pop(0)
	for x in mm[t]:
		if dp[x] > dp[t] + 1:
			dp[x] = dp[t] + 1
			queue.append(x)
		else:
			pass
			
for i,x in enumerate(queue):
	if i == 0:
		pass
	else:
		if x == float('inf'):
			print(i, -1)
		else:
			print(i, x)

Python: import collections

N = int(input())
M = []
for i in range(N):
    a = list(map(int,input().strip().split()))
    b = [int(i+1 in a[2:]) for i in range(N)]
    M.append(b)

D = [-1 for _ in range(N)]
D[0] = 0 # 始点への距離は 0, 他の距離は-1
Q = collections.deque()
Q.append(0) # 始点
while len(Q) > 0:
    #print("bfs", Q) # 各ステップでの Q の動作を確認
    cur = Q.popleft()
    for dst in range(N):
        # curからdstに移動可能かつ、dstが未訪問だったら
        if M[cur][dst] == 1 and D[dst] == -1:
            D[dst] = D[cur]+1
            Q.append(dst) # Qにdstを詰める
for v in range(N):
    print(v+1, D[v])

Python: import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001

class Info:
    def __init__(self,arg_node_id,arg_sum_cost):
        self.node_id = arg_node_id
        self.sum_cost = arg_sum_cost


V = int(input())
ADJ = [[] for i in range(V)]

for loop in range(V):
    input_str = list(map(int,input().split()))
    node_id = input_str[0]-1
    for i in range(input_str[1]):
        ADJ[node_id].append(input_str[2+i]-1)

visited = [False]*V
visited[0] = True

min_dist = [-1]*V
min_dist[0] = 0

Q = deque()
Q.append((Info(0,0)))

while len(Q) > 0:
    info = Q.popleft()
    for next_node in ADJ[info.node_id]:
        if visited[next_node] == True:
            continue
        visited[next_node] = True
        min_dist[next_node] = info.sum_cost+1
        Q.append((Info(next_node,min_dist[next_node])))

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

Python: from collections import deque
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
    u, _, *v = map(lambda x: int(x)-1, input().split())
    edge[u] = v
dist = [-1] * V
dist[0] = 0
que = deque([0])

while len(que):
    v = que.popleft()
    for c in edge[v]:
        if dist[c] == -1:
            dist[c] = dist[v] + 1
            que.append(c)
for i, d in enumerate(dist):
    print(i+1, 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
    isDiscovered [x] = True
    time_stamp += 1
    for i in a[x]:
        if not isDiscovered[i]:
            d[i] = d[x] + 1

bfs(0)
d_ = 1
while not(isDiscovered == [True] * n):
    for i in range(n):
        if d[i] is d_ and not isDiscovered[i]:
            bfs(i)
    d_ += 1

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