Go: package main

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

const MAX = 1000
const NIL = -1

type Node struct {
	id    int
	depth int
}

type Queue struct {
	head      int
	tail      int
	container [MAX]Node
}

func (q *Queue) inQueue(x Node) {
	q.container[q.tail] = x
	q.tail = (q.tail + 1) % MAX
}

func (q *Queue) deQueue() Node {
	x := q.container[q.head]
	q.head = (q.head + 1) % MAX
	return x
}

func (q *Queue) isEmpty() bool {
	return q.head == q.tail
}

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInt()
	route := make([][]int, n)
	for i := range route {
		u, k := scanInt(), scanInt()
		u--
		route[u] = make([]int, k)
		for j := range route[u] {
			num := scanInt()
			num--
			route[i][j] = num
		}
	}

	d := make([]int, n)
	for i := range d {
		d[i] = NIL
	}

	start := Node{0, 0}
	que := Queue{}
	que.inQueue(start)
	for !que.isEmpty() {
		node := que.deQueue()
		if d[node.id] != NIL {
			continue
		}
		d[node.id] = node.depth

		for _, nextId := range route[node.id] {
			next := Node{id: nextId, depth: node.depth + 1}
			que.inQueue(next)
		}
	}

	for i, depth := range d {
		fmt.Println(i+1, depth)
	}
}

Python: from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  for i in range(n):
    if visited[i] == 1:
      continue
    visited[i] = 1
    bfs(i)
  for i, d in enumerate(dis):
    print(i, d)

Python: # -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [-1 for _ in range(n)]
d[0] = 0


for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    #print(*adj[u-1])

stack = [0]

while stack:
    #print(stack)
    current = stack[-1]
    flag = 0
    for k in adj[current]:
        if d[k] < 0:
            d[k] = d[current]+1
            stack.append(k)
            flag = 1
        elif d[k] > d[current]+1:
            d[k] = d[current]+1
    if flag == 0:
        stack.pop()

    #print('current = {}, t = {}'.format(current, t))
    #print('stack', *stack)

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

Python: from collections import deque
from collections import defaultdict

n = int(input())

graph = defaultdict(list)

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

ans = [-1] * (n + 1)

q = deque([1])
ans[1] = 0

while q:
    c = q.popleft()
    for v in graph[c]:
        if ans[v] == -1:
            ans[v] = ans[c] + 1
            q.append(v)

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

Python: from collections import deque

# リストでグラフを表現する
n = int(input())
G = [input().split()[2:] for _ in range(n)]

# 頂点1から各頂点への距離を-1 (頂点1からたどり着けない)で初期化する
d = [-1] * n

que = deque()  # 訪問予定の頂点を格納する

# 初期状態をキューに入れる
que.append(0)
d[0] = 0

while que:
    p = que.popleft()  # FIFOでキューの要素を取り出し、その頂点を訪ねる。
    for v in G[p]:
        v = int(v) - 1
        if d[v] < 0:  # まだ訪れたことがない
            que.append(v)
            # 距離を記録する
            d[v] = d[p] + 1


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

Python: def bfs(graph, start, result):
    visited = {start: None}
    unvisited = [start]
    while unvisited:
        now = unvisited[0]
        unvisited = unvisited[1:]
        if visited[now] == None:
            result[now] = 0
        else:
            result[now] = result[visited[now]] + 1
        for next in graph[now][2:]:
            if not (next in visited):
                unvisited.append(next)
                visited[next] = now
    return visited

n = int(input())
g = [[]]
r = {i: -1 for i in range(n + 1)}

for i in range(n):
    g.append(list(map(int, input().split())))

v = bfs(g, 1, r)

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

Python: import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array

# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
# from decimal import Decimal
# from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    visited = [-1] * N
    G = [[False] * N for _ in range(N)]
    for n in range(N):
        u, k, *V = il()
        for v in V:
            G[n][v - 1] = True

    que = queue.Queue()
    que.put(0)
    visited[0] = 0
    while not que.empty():
        now = que.get()
        for n in range(N):
            if G[now][n] and visited[n] == -1:
                visited[n] = visited[now] + 1
                que.put(n)

    for n in range(N):
        print(n + 1, visited[n])


if __name__ == '__main__':
    main()

Python: from collections import deque
n = int(input())
graph = [[] for _ in range(n)]
global Q, S, T
global visited, dis
Q = deque([0])
S = [0] #訪れた順
T = []
visited = [0 for _ in range(n)]
dis = [-1 for _ in range(n)] #初めからの距離
dis[0] = 0
def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def bfs(node_id):
  global Q, S
  while Q:
    node_id = Q.popleft()

    for ad_node in graph[node_id]:
      if visited[ad_node] == 1:
        continue
      visited[ad_node] = 1
      dis[ad_node] = dis[node_id] + 1
      S.append(ad_node)
      Q.append(ad_node)

if __name__ == "__main__":
  input_graph(n)
  bfs(0)
  for i, d in enumerate(dis):
    print(i+1, d)