Go: package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	num, _ := strconv.Atoi(sc.Text())
	nodes := make(map[int]*node)

	for i := 0; i < num; i++ {
		sc.Scan()
		id, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		nodeNum, _ := strconv.Atoi(sc.Text())
		n := node{id, make([]int, 0), -1}
		for j := 0; j < nodeNum; j++ {
			sc.Scan()
			nid, _ := strconv.Atoi(sc.Text())
			n.nexts = append(n.nexts, nid)
		}
		nodes[id] = &n
	}
	nodes[1].depth = 0

	walk(1, 0, &nodes)
	for i := 1; i < len(nodes)+1; i++ {
		fmt.Printf("%v %v\n", (*nodes[i]).id, (*nodes[i]).depth)
	}
}

var time int
var record [100][100]bool
var q Queue

func walk(nid int, from int, nodes *map[int]*node) {
	q.Enqueue((*nodes)[nid])
	for !q.IsEmpty() {
		n := q.Dequeue().(*node)
		for _, v := range n.nexts {
			n2 := (*nodes)[v]
			if n2.depth != -1 {
				continue
			}
			n2.depth = n.depth + 1
			q.Enqueue((*nodes)[v])
		}
	}
}

type node struct {
	id    int
	nexts []int
	depth int
}

// Queue is Queue
type Queue struct {
	val []interface{}
}

// Enqueue value
func (queue *Queue) Enqueue(val interface{}) {
	queue.val = append(queue.val, val)
}

// Dequeue value
func (queue *Queue) Dequeue() interface{} {
	res := queue.val[0]
	queue.val = queue.val[1:len(queue.val)]
	return res
}

// IsEmpty return true when queue is empty
func (queue *Queue) IsEmpty() bool {
	return len(queue.val) == 0
}

Python: #!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys


def bfs(matrix):
    distances = [-1 for _ in range(len(matrix))]
    queue = [0]
    distances[0] = 0

    while 0 < len(queue):
        node_id = queue.pop(0)  # Dequeue
        distance = distances[node_id]
        for index, candidate in enumerate(matrix[node_id]):
            if candidate == 1 and distances[index] == -1:
                # ???????????¢????¨?????????????????????? node
                queue.append(index)
                distances[index] = distance + 1

    return distances

if __name__ == "__main__":
    # ??????????????????
    # lines = [
    #     "4",
    #     "1 2 2 4",
    #     "2 1 4",
    #     "3 0",
    #     "4 1 3",
    # ]
    lines = sys.stdin.readlines()
    dimension = int(lines[0])
    matrix = [[0 for _ in range(dimension)] for _ in range(dimension)]

    # Set edge info
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    distances = bfs(matrix)
    for index, distance in enumerate(distances):
        print("%d %d" % (index + 1, distance))

Python: from collections import deque
from typing import List
import sys


def bfs(adj_list: List[List[int]]) -> List[int]:
    n = len(adj_list)
    result: List[int] = [sys.maxsize for _ in range(n)]
    result[0] = 0
    queue: deque = deque()
    queue.append(0)

    while len(queue) > 0:
        cur = queue.popleft()
        for vertex in adj_list[cur]:
            if result[cur] + 1 < result[vertex]:
                result[vertex] = result[cur] + 1
                queue.append(vertex)

    return result


if __name__ == "__main__":
    num_vertices = int(input())
    adj_list: List[List[int]] = [[] for _ in range(num_vertices)]

    for _ in range(num_vertices):
        vertex, num_adjs, *adjs = map(lambda x: int(x), input().split())
        for i in range(num_adjs):
            adj_list[vertex - 1].append(adjs[i] - 1)

    result = bfs(adj_list)

    for i in range(num_vertices):
        if sys.maxsize == result[i]:
            result[i] = -1
        print(f"{i + 1} {result[i]}")

Python: #coding:utf-8
                
def BFS(i,A,d,dist):
    dist[i]=d
    for point in A[i]:
        if dist[point-1]==-1 or dist[point-1]>d+1:
            BFS(point-1,A,d+1,dist)

if __name__=="__main__":
    n=int(input())
    A=[]
    for i in range(n):
        A.append(list(map(int,input().split(" ")))[2:])
    dist=[-1]*n
    BFS(0,A,0,dist)

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

Python: import collections

N = int(input())
G = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
    u,k,*varray = map(int,input().split())
    for v in varray:
        G[u-1][v-1] = 1
        
D = [-1 for _ in range(N)]
D[0] = 0
Q = collections.deque()
Q.append(0)
while len(Q) > 0:
    # print("bfs",Q)
    cur = Q.popleft()
    for dst in range(N):
        if G[cur][dst] == 1 and D[dst] == -1:
            D[dst] = D[cur] + 1
            Q.append(dst)
for v in range(N):
    print(v+1, D[v])
            

# 順番を書こう。落ち着け
# まずd=1の時→行列の一行目をみよう
# 1になっている列を探す→そいつらのDは全部2に変える
# プラスしてそいつらのしもべたちを3にする
#

Python: import queue

N = int(input())
L = [list(map(int,input().split())) for _ in range(N)]
V = [(i+1) for i in range(N)]
E = []
for i in range(N):
    for j in range(len(L[i])-2):
        E.append((i+1,L[i][j+2]))

class Graph:
    def __init__(self,v,e):
        self.v = v
        self.e = e
        self.v_visited = [False for _ in range(N)]
    def visited(self,v):
        self.v_visited[v-1] = True

q = queue.Queue()
g = Graph(V,E)
TS = [-1 for _ in range(N)]

def bfs(u):
    q.put(u)
    g.visited(u)
    TS[u-1] = 0
    while not q.empty():
        u = q.get()
        for v in g.v:
            if (u,v) in g.e and g.v_visited[v-1] == False:
                q.put(v)
                g.visited(v)
                TS[v-1] = TS[u-1]+1
bfs(1)

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

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])