Go: package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

const (
	N     = 100
	INFTY = 1 << 21
)

type Graph struct {
	M [N][N]int
	d [N]int
}

func (g *Graph) bfs(s, n int) string {
	var q []int
	q = append(q, s) // push

	for i := 0; i < n; i++ {
		g.d[i] = INFTY
	}
	g.d[s] = 0

	for len(q) != 0 {
		u := q[0]
		q = q[1:] // pop
		for v := 0; v < n; v++ {
			if g.M[u][v] == 0 || g.d[v] != INFTY {
				continue
			}
			g.d[v] = g.d[u] + 1
			q = append(q, v) // push
		}
	}

	var out bytes.Buffer
	for i := 0; i < n; i++ {
		if g.d[i] == INFTY {
			out.WriteString(fmt.Sprintf("%d -1\n", i+1))
			continue
		}
		out.WriteString(fmt.Sprintf("%d %d\n", i+1, g.d[i]))
	}

	return strings.TrimRight(out.String(), "\n")
}

func answer(reader io.Reader) string {
	sc := bufio.NewScanner(reader)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())

	var g Graph
	for i := 0; i < n; i++ {
		sc.Scan()
		u, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		k, _ := strconv.Atoi(sc.Text())
		u--
		for j := 0; j < k; j++ {
			sc.Scan()
			v, _ := strconv.Atoi(sc.Text())
			v--
			g.M[u][v] = 1
		}
	}

	return g.bfs(0, n)
}

func main() {
	fmt.Println(answer(os.Stdin))
}

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

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