Go: package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)

	g := make([][]int, n+1)
	d := make([]int, n+1)
	for i := 0; i < n; i++ {
		var u,k int
		fmt.Scan(&u)
		fmt.Scan(&k)
		g[u] = make([]int, k)
		for j := 0; j < k; j++ {
			fmt.Scan(&g[u][j])
		}

		d[i+1] = -1
	}

	q := [][]int{}
	q = append(q, []int{1, 0})
	for len(q) > 0 {
		pop := q[0]
		if len(q) > 1 {
			q = q[1:]
		} else {
			q = [][]int{}
		}
		if d[pop[0]] >= 0 {
			continue
		}
		d[pop[0]] = pop[1]

		for j := 0; j < len(g[pop[0]]); j++ {
			q = append(q, []int{g[pop[0]][j], pop[1]+1})
		}
	}

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

Python: from collections import deque
import sys
input = sys.stdin.readline

n = int(input())
graph = {i: deque() for i in range(1, n+1)}

for i in range(n):
    u, k, *v = map(int, input().split())
    v.sort()
    for vi in v:
        graph[u].append(vi)

seen = [0]*(n+1)
queue = deque()
dist = [-1]*(n+1)
def bfs(v):
    dist[v] = 0
    seen[v] = 1
    queue.append(v)
    while queue:
        q = queue[0]
        if not graph[q]:
            queue.popleft()
            continue
        g = graph[q].popleft()
        if seen[g]:
            continue
        seen[g] = 1
        dist[g] = dist[q] + 1
        queue.append(g)

bfs(1)
for id, d in enumerate(dist):
    if id == 0:
        continue
    print(id, d)

Python: from collections import deque
from enum import Enum, auto

class Color(Enum):
    WHITE = auto()
    GRAY = auto()
    BLACK = auto()

n = int(input())
d = [0 for i in range(n)]
f = [0 for i in range(n)]

colors = [] # 頂点の訪問状態
A = [[0 for j in range(n)] for i in range(n)] # 隣接行列
queue = deque([])

# 隣接行列の初期化
for i in range(n):
    arr = list(map(int, input().split(' ')))
    u, k, v = arr[0], arr[1], arr[2:]
    for j in range(k):
        A[u-1][v[j]-1] = 1

def bfs():
    global colors, queue, d
    colors = [Color.WHITE for i in range(n)]
    d = [-1 for i in range(n)] # INF

    colors[0] = Color.GRAY
    d[0] = 0
    queue.append(0)

    while len(queue) > 0:
        u = queue.pop()
        for v in range(n):
            if A[u][v] == 1 and colors[v] == Color.WHITE:
                colors[v] = Color.GRAY
                d[v] = d[u] + 1
                queue.append(v)
        colors[u] = Color.BLACK

bfs()

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

Python: import collections

n=int(input())
adj=[]
for i in range(n):
      adj.append(list(map(int, input().split())))

Q=[]
Q=collections.deque()
Q.append(0)

D=[-1 for i in range(n)]
D[0]=0

while len(Q)>0:
    current=Q.popleft()
    for dst in range(n):
        for i in range(2,len(adj[current])):
            if adj[current][i]==dst+1 and D[dst]==-1:
                D[dst]=D[current]+1
                Q.append(dst)
for i in range(n):
    print(i+1,D[i])

Python: from collections import deque
import sys


def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())


class Graph:
    def __init__(self, n, is_directed=False):
        """
        :param n: 頂点数
        :param is_directed: 有向グラフ(True)か無向グラフか(False)
        """
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.is_directed = is_directed

    def add_edge(self, u, v):
        """uからvへの(有向な)辺をつなぐ"""
        self.graph[u].append(v)
        if not self.is_directed:
            self.graph[v].append(u)

    def search(self, start, mode):
        '''開始地点から各頂点まで幅/深さ優先探索を行って得られた距離のリストを返す
        Args:
          start(int): 開始地点となる頂点
          mode(str): 幅優先探索(b)か深さ優先探索(d)を指定

        Returns:
          List[int]: 開始地点からの距離(未到達の場合は-1)
        '''
        dists = [-1] * self.n
        que = deque([start])
        dists[start] = 0
        if mode == 'b':
            get_v = que.popleft
        else:
            get_v = que.pop
        while que:
            now_v = get_v()
            for next_v in self.graph[now_v]:
                if dists[next_v] != -1:
                    continue
                que.append(next_v)
                dists[next_v] = dists[now_v] + 1
        return dists


n = I()
g = Graph(n, is_directed=True)
for _ in range(n):
    u, k, *v = LI()
    u -= 1
    if v == []:
        continue
    for vi in v:
        vi -= 1
        g.add_edge(u, vi)
res = g.search(0, 'b')
for i in range(n):
    print(i + 1, res[i])

Python: from collections import deque

icase=0
if icase==0:
    n=int(input())
    u=[0]*n
#    g = [deque([]) for _ in range(n)]
    g = [[] for _ in range(n)]
    for i in range(n):
        ukv=list(map(int,input().split()))
        u[i]=ukv[0]-1
        ki=ukv[1]
        v=ukv[2:]
        for vi in v:
            g[u[i]].append(vi-1)
#            g[vi-1].append(u[i])
elif icase==1:
    n=4
    g = [[] for _ in range(n)]
    g[0]=[1,3]
    g[1]=[0,3]
    g[2]=[3]
    g[3]=[0,1,2]
#ans:0 1 2 1

q=deque([0])

stack=[0]
parent=[-1]*n
parent[0]=0
dist=[-1]*n
dist[0]=0
while q:
    state = q.popleft()
#    print("--- q:",q,"state:",state,"g:",g[state],"p:",parent)
    for v in g[state]:
#        print("  state:",state,"v:",v,"q:",q)
#        if parent[state] == v:
        if parent[v] !=-1:
            continue
        else:
#            print("parent:",parent,"xx:",xx,"stack",stack)
            parent[v]=state
            dist[v]=dist[state]+1
            q.append(v)
#            print(" state:",state,"v:",v,"parent:",parent,"stack",stack,"dist[v]",dist[v])

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

Python: import sys
from collections import deque

inf = 1<<30

def solve():
    n = int(input())
    Adj = [None] * n

    for i in range(n):
        u, k, *line = [int(i) - 1 for i in input().split()]
        Adj[u] = line

    d = bfs(n, Adj)

    for i, di in enumerate(d, start=1):
        if di == inf:
            print(i, -1)
        else:
            print(i, di)

def bfs(n, Adj):
    d = [inf] * n
    d[0] = 0
    nxts = deque([0])

    while nxts:
        u = nxts.popleft()

        for v in Adj[u]:
            if d[v] == inf:
                d[v] = d[u] + 1
                nxts.append(v)

    return d

if __name__ == '__main__':
    solve()

Python: def bfs(adj, s):
    n = len(adj)
    d = [-1 for _ in range(n)]
    c = [0 for _ in range(n)]

    d[s] = 0
    c[s] = 1

    queue = [s]

    while len(queue) > 0:
        u = queue.pop(0)
        for v in adj[u]:
            if c[v] == 0:
                c[v] = 1
                d[v] = d[u] + 1
                queue.append(v)

    return d


n = int(input())
adj = [[] for _ in range(n)]
for _ in range(n):
    s = [int(x) for x in input().split()]
    u = s[0]
    for v in s[2:]:
        adj[u - 1].append(v - 1)

d = bfs(adj, 0)

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

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	breadth_first_search
# CreatedDate:  2020-04-14 23:40:14 +0900
# LastModified: 2020-04-15 00:14:09 +0900
#


import os
import sys
from collections import deque

def bfs(matrix,n):
    s=0
    color=[0]*n
    color[s]=1
    Q=deque()
    Q.append(s)
    distance = [-1]*n
    distance[0]=0
    while Q:
        u = Q.popleft()
        for v in matrix[u]:
            if color[v]==0:
#                print("{}->{}".format(u,v))
                distance[v]=distance[u]+1
                color[v]=1
                Q.append(v)
        color[u]=2
    
    return distance

def main():
    n=int(input())
    matrix = [[] for _ in range(n)]
    for i in range(n):
        lined = map(int,input().split())
#        print(lined)
        for j,pon in enumerate(lined):
            if j>=2:
                matrix[i].append(pon-1)
#    print(matrix)
    distance = bfs(matrix,n)
    for i,di in enumerate(distance):
        print("{} {}".format(i+1,di))

if __name__ == "__main__":
    main()